Tensorum
LeetCode 173 · Iterator (Stack-based)

Binary Search Tree Iterator

LeetCode 173 · Medium · solution, intuition & step-by-step walkthrough

Controlled in-order traversal with a stack of left spines.

MediumStackTreeDesignBinary Search TreeBinary Tree
12 msruntime · beats 81%
63.5 MBmemory · beats 100%
1approach
7accepted runs · last 14 Dec 2024

This is how I solved Binary Search Tree Iterator (LeetCode 173), a medium problem from the Iterator (Stack-based) pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

An in-order traversal, paused. Keep a stack with the path of left children; the top is always the next smallest. After returning a node, push the left spine of its right subtree.

Approach

  1. 1

    Constructor: push root and all its left descendants.

  2. 2

    next: pop a node, push the left spine of node.right, return node.val.

  3. 3

    hasNext: stack is not empty.

How I solved it

Stack of left spinesPythonO(1) amortised · O(h) space
class BSTIterator:
    def __init__(self, root):
        self.stack = []
        self.pushAll(root)  # always push extreme left items first

    def next(self):
        if len(self.stack) != 0:
            node = self.stack.pop()
            if node is not None:
                self.pushAll(node.right)  # go right and push all left nodes
            return node.val

    def hasNext(self):
        return len(self.stack) != 0

    def pushAll(self, node):
        cur = node
        while cur is not None:
            self.stack.append(cur)
            cur = cur.left
Loading the step-through…

Binary Search Tree Iterator — FAQ

What is the intuition behind Binary Search Tree Iterator?

An in-order traversal, paused. Keep a stack with the path of left children; the top is always the next smallest. After returning a node, push the left spine of its right subtree.

How do you solve Binary Search Tree Iterator (LeetCode 173)?

1. Constructor: push root and all its left descendants. 2. next: pop a node, push the left spine of node.right, return node.val. 3. hasNext: stack is not empty.

What is the time and space complexity of Binary Search Tree Iterator?

Time: O(1) amortised next. Space: O(h). (Accepted approach: Stack of left spines.)

What are common mistakes in Binary Search Tree Iterator?

Flattening the whole tree up front uses O(n) memory instead of O(h).