Binary Search Tree Iterator

Pattern: BST iterator

medium

Keep a stack holding the path of nodes not yet visited, smallest on top: at the start, push the root and its far-left chain. next() pops a node, pushes the far-left chain of its right child, and returns the node's value. hasNext() checks the stack.

The problem

Build BSTIterator(root) with next(), returning the next value in increasing order, and hasNext(). next() is only called when a value remains. Both should be O(1) on average with O(h) memory.

Think first

  • Which value does the first next() return?
  • After returning a node, which values come next?
  • What should the stack hold?

Hints

    Brute force, and why it fails

    Store the whole inorder in a list at the start: O(n) memory.

    The key insight

    The stack is a paused inorder walk, so each node is pushed and popped once over all calls.

    Dry run

    stack7 3

    BST [7, 3, 15, null, null, 9, 20]. Start: push 7, 3.

    Step 1 of 3

    The plan

    init: pushLeft(root)
    next: n = pop; pushLeft(n.right); return n.val
    hasNext: stack not empty
    

    Complexity

    Time
    O(1) amortised per call
    Space
    O(h)

    n calls push and pop n nodes in total.

    Edge cases

    • One node.
    • A right chain.
    • A left chain.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class BSTIterator {
        private final Deque<TreeNode> st = new ArrayDeque<>();   // the path of nodes still to visit, smallest on top
    
        public BSTIterator(TreeNode root) {
            pushLeft(root);
        }
    
        public int next() {
            TreeNode n = st.pop();
            pushLeft(n.right);                      // its right subtree comes next, starting from its far left
            return n.val;
        }
    
        public boolean hasNext() {
            return !st.isEmpty();
        }
    
        private void pushLeft(TreeNode n) {
            for (; n != null; n = n.left) st.push(n);
        }
    }

    C++

    class BSTIterator {
    public:
        stack<TreeNode*> st;                        // the path of nodes still to visit, smallest on top
    
        BSTIterator(TreeNode* root) {
            pushLeft(root);
        }
    
        int next() {
            TreeNode* n = st.top();
            st.pop();
            pushLeft(n->right);                     // its right subtree comes next, starting from its far left
            return n->val;
        }
    
        bool hasNext() {
            return !st.empty();
        }
    
        void pushLeft(TreeNode* n) {
            for (; n != NULL; n = n->left) st.push(n);
        }
    };

    Python

    class BSTIterator:
        def __init__(self, root):
            self.st = []                            # the path of nodes still to visit, smallest on top
            self.push_left(root)
    
        def next(self) -> int:
            n = self.st.pop()
            self.push_left(n.right)                 # its right subtree comes next, starting from its far left
            return n.val
    
        def hasNext(self) -> bool:
            return bool(self.st)
    
        def push_left(self, n) -> None:
            while n:
                self.st.append(n)
                n = n.left

    Common mistakes

    • Pushing the right child but not its left chain.
    • Precomputing everything.

    Similar problems