Algo-Sim › Binary Trees & BST

Binary Search Tree Iterator

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

A controlled inorder walk: the stack holds the left spine still to visit, so next() is amortized O(1) with O(h) memory.

Problem

Build an iterator over a binary search tree that returns its values in ascending order. next() returns the next smallest value and hasNext() says whether any are left. Use O(h) memory, where h is the height of the tree.

Constraints

Edge cases to test

Follow-up questions

Why is next O(1) amortized?
Each node is pushed and popped once over the whole iteration, so n calls cost O(n) in total.
How do you add prev?
Keep a list of values already returned and an index into it; move the stack only when going past the end (LC 1586).

Solution

Java

class BSTIterator {
    private final Deque<TreeNode> stack = new ArrayDeque<>();

    public BSTIterator(TreeNode root) {
        pushLeft(root);
    }

    private void pushLeft(TreeNode node) {
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
    }

    public int next() {
        TreeNode node = stack.pop();
        pushLeft(node.right);
        return node.val;
    }

    public boolean hasNext() {
        return !stack.isEmpty();
    }
}

Python

class BSTIterator:
    def __init__(self, root):
        self.stack = []
        self.push_left(root)

    def push_left(self, node):
        while node:
            self.stack.append(node)
            node = node.left

    def next(self):
        node = self.stack.pop()
        self.push_left(node.right)
        return node.val

    def hasNext(self):
        return len(self.stack) > 0

C++

#include <bits/stdc++.h>
using namespace std;

class BSTIterator {
    stack<TreeNode *> nodes;

    void pushLeft(TreeNode *node) {
        while (node != nullptr) {
            nodes.push(node);
            node = node->left;
        }
    }

  public:
    BSTIterator(TreeNode *root) {
        pushLeft(root);
    }

    int next() {
        TreeNode *node = nodes.top();
        nodes.pop();
        pushLeft(node->right);
        return node->val;
    }

    bool hasNext() {
        return !nodes.empty();
    }
};

More Binary Trees & BST problems