Video in progress

How do you traverse a binary tree in inorder without recursion?

With a stack: from the current node I go left, pushing every node on the way. When the left side runs out, I pop one from the stack, record its value and move to its right child. Each node goes in and out once, so it's O(n).

📖 Answer

There are three classic orders: preorder (node, left, right), inorder (left, node, right), postorder (left, right, node). In a BST, inorder gives the values in ascending order, which is why it is asked most often.

record TreeNode(int val, TreeNode left, TreeNode right) {}

static List<Integer> inorder(TreeNode root) {
    List<Integer> out = new ArrayList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode cur = root;
    while (cur != null || !stack.isEmpty()) {
        while (cur != null) {          // all the way left
            stack.push(cur);
            cur = cur.left();
        }
        cur = stack.pop();
        out.add(cur.val());
        cur = cur.right();
    }
    return out;
}

Why without recursion? If the tree is unbalanced (for example a BST built from sorted data, which is effectively a chain), the depth equals n. At 100,000 nodes, recursion overflows the stack.

Pay attention to the loop condition: cur != null || !stack.isEmpty(). If you check only the stack, the loop never starts, because the stack is empty at the beginning.

Iterative preorder is even simpler: you take a node, record it, and push the right child first and then the left child onto the stack.