AlgoMaster Logo

Binary Tree Inorder Traversal

tree=[1, 2, 3, 4, 5, null, 8, null, null, 6, 7, 9]
1public List<Integer> inorderTraversal(TreeNode root) {
2    List<Integer> result = new ArrayList<>();
3    Stack<TreeNode> stack = new Stack<>();
4    TreeNode current = root;
5
6    while (!stack.isEmpty() || current != null) {
7        // Reach the leftmost node of the current node
8        while (current != null) {
9            stack.push(current);
10            current = current.left;
11        }
12
13        // Current must be null at this point
14        current = stack.pop();
15        result.add(current.val); // Visit the node
16
17        // We have visited the node and its left subtree. Now, visit the right subtree
18        current = current.right;
19    }
20
21    return result;
22}
0 / 74
RL123458679Stack