Binary Search Tree Iterator

Implement an iterator over a binary search tree.

It will be initialized with the root node of a BST.

Example

// root is the root node of BST [4,2,10,1,3,6,11]
BSTIterator iter = new BSTIterator(root);
while (iter.hasNext()) print iter.next() + ",";
// output: 1,2,3,4,6,10,11

Approach

Iterative inorder traversal

Code

public class BSTIterator {
    private Stack<TreeNode> stack;
    private TreeNode current;

    /** Initialize the stack */
    public BSTIterator(TreeNode root) {
        stack = new Stack<TreeNode>();
        current = root;
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        // we are not at the bottom right of the BST
        return (!stack.isEmpty() || current != null);
    }

    /** @return the next smallest number */
    public int next() {
        int smallest;
        // left child first
        while (current != null) {
            stack.push(current);
            current = current.left;
        } 
        // backtrack to parent
        // log inorder
        current = stack.pop();
        smallest = current.val;
        // right child last
        current = current.right;
        return smallest;
    }
}

To some degree, each next() is kind of like a recursive call, given a new root and perform the in-order traversal from there.

Reading

Traversing binary trees simply and cheaply by Joseph M. Morris

Last updated