173. Binary Search Tree Iterator
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to implement an iterator for a Binary Search Tree (BST) that returns nodes in in-order sequence. An in-order traversal of a BST visits nodes in ascending order of their values. The key challenge is to design next() and hasNext() to have an average time complexity of O(1) while using O(h) memory, where h is the height of the tree, as suggested in the follow-up.
Solution
Binary Search Tree Iterator in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.stack = []
# In the constructor, we push all the left children onto the stack.
self._push_left(root)
def next(self) -> int:
# The top of the stack is the next node in the in-order traversal.
# Note: next() is guaranteed to be called only when hasNext() is true.
node = self.stack.pop()
# After processing the node, we need to explore its right subtree
# to find the next smallest elements.
self._push_left(node.right)
return node.val
def hasNext(self) -> bool:
# If the stack is not empty, it means there are still nodes to visit.
return len(self.stack) > 0
def _push_left(self, node: Optional[TreeNode]):
# Helper function to push a node and all its left descendants to the stack.
while node:
self.stack.append(node)
node = node.left
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
Binary Search Tree Iterator in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.Stack;
class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
// Initialize the stack.
this.stack = new Stack<>();
// Push all the left children of the root onto the stack.
this.pushLeft(root);
}
public int next() {
// The node at the top of the stack is the next smallest element.
// Note: next() is guaranteed to be called only when hasNext() is true.
TreeNode node = this.stack.pop();
// The next element in order is the smallest element in the right subtree.
// Push all left children of the right child onto the stack.
if (node.right != null) {
this.pushLeft(node.right);
}
return node.val;
}
public boolean hasNext() {
// If the stack is not empty, there are more elements.
return !this.stack.isEmpty();
}
private void pushLeft(TreeNode node) {
// Push the node and all its left children onto the stack.
while (node != null) {
this.stack.push(node);
node = node.left;
}
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
Binary Search Tree Iterator in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include <stack>
class BSTIterator {
private:
std::stack<TreeNode*> st;
// Helper function to push all left children of a node onto the stack.
void pushAllLeft(TreeNode* node) {
while (node != nullptr) {
st.push(node);
node = node->left;
}
}
public:
BSTIterator(TreeNode* root) {
// Initialize the iterator by pushing the path to the smallest element.
pushAllLeft(root);
}
int next() {
// The top of the stack is the next smallest element.
// Note: next() is guaranteed to be called only when hasNext() is true.
TreeNode* topNode = st.top();
st.pop();
// Before returning, prepare for the next call.
// The next element is the smallest in the right subtree of the current node.
if (topNode->right != nullptr) {
pushAllLeft(topNode->right);
}
return topNode->val;
}
bool hasNext() {
// If the stack is not empty, there is a next element.
return !st.empty();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
Binary Search Tree Iterator in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
class BSTIterator {
private stack: TreeNode[];
constructor(root: TreeNode | null) {
this.stack = [];
this.pushLeft(root);
}
next(): number {
// The node at the top of the stack is the next smallest element.
// The problem guarantees next() is valid, so stack is not empty, hence the non-null assertion.
const node = this.stack.pop()!;
// The next in-order element is the smallest element in the right subtree.
// Push the right child and all its left descendants.
if (node.right) {
this.pushLeft(node.right);
}
return node.val;
}
hasNext(): boolean {
// If the stack has elements, there is a next element.
return this.stack.length > 0;
}
private pushLeft(node: TreeNode | null): void {
// Helper to push a node and all its left children onto the stack.
while (node) {
this.stack.push(node);
node = node.left;
}
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* var obj = new BSTIterator(root)
* var param_1 = obj.next()
* var param_2 = obj.hasNext()
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.