Binary Tree Inorder Traversal

Pattern: Traversals

easy

Inorder visits the left subtree, then the node, then the right subtree. Iteratively: walk left pushing nodes onto a stack; pop one, record it, then move to its right child and repeat.

The problem

Return the inorder traversal of a binary tree: left subtree, node, right subtree. [1, null, 2, 3] gives [1, 3, 2]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • Which node is visited first?
  • What must you remember while going left?
  • After visiting a node, where do you go?

Hints

    Brute force, and why it fails

    The recursive version is three lines: visit(left); record; visit(right). It is O(n) too, but uses the call stack.

    The key insight

    An explicit stack replays exactly what the recursion would do, so the order is the same with no recursion.

    Dry run

    stack1
    out

    root = [1, null, 2, 3]: 1 has right child 2, and 2 has left child 3. Push 1; it has no left.

    Step 1 of 3

    The plan

    cur = root
    while cur or stack:
        while cur: push cur; cur = cur.left
        cur = pop; record cur
        cur = cur.right
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    Each node is pushed and popped once; the stack holds at most one path.

    Edge cases

    • Empty tree: an empty list.
    • One node.
    • A tree that is a single long chain: the stack grows to n.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> out = new ArrayList<>();
            Deque<TreeNode> stack = new ArrayDeque<>();
            TreeNode cur = root;
            while (cur != null || !stack.isEmpty()) {
                while (cur != null) {               // go as far left as possible, remembering the way back
                    stack.push(cur);
                    cur = cur.left;
                }
                cur = stack.pop();                  // the leftmost node not yet visited
                out.add(cur.val);
                cur = cur.right;                    // then its right subtree
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            vector<int> out;
            stack<TreeNode*> st;
            TreeNode* cur = root;
            while (cur != NULL || !st.empty()) {
                while (cur != NULL) {               // go as far left as possible, remembering the way back
                    st.push(cur);
                    cur = cur->left;
                }
                cur = st.top();                     // the leftmost node not yet visited
                st.pop();
                out.push_back(cur->val);
                cur = cur->right;                   // then its right subtree
            }
            return out;
        }
    };

    Python

    class Solution:
        def inorderTraversal(self, root) -> list[int]:
            out, stack, cur = [], [], root
            while cur or stack:
                while cur:                          # go as far left as possible, remembering the way back
                    stack.append(cur)
                    cur = cur.left
                cur = stack.pop()                   # the leftmost node not yet visited
                out.append(cur.val)
                cur = cur.right                     # then its right subtree
            return out

    Common mistakes

    • Recording a node when it is pushed (that is preorder).
    • Forgetting to move to the right child after recording.

    Similar problems