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
- 1 ≤ number of nodes ≤ 10⁵
- 0 ≤ Node.val ≤ 10⁶
- next() is only called when a value is left
- Follow-up: amortized O(1) per call and O(h) memory
Edge cases to test
- Empty tree:
hasNextis false - A right-only chain
- Calling
nexton the last value
Follow-up questions
- Why is
nextO(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) > 0C++
#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
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)