Skip to content

Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST. Calling hasNext() will return whether there are any more elements in the iterator.

Input (BST)Operation SequenceOutput/BehaviorExplanation
[7,3,15,null,null,9,20]hasNext(), next(), next(), hasNext(), next()true, 3, 7, true, 9In-order: [3, 7, 9, 15, 20]
[1,null,2]hasNext(), next(), hasNext(), next()true, 1, true, 2In-order: [1, 2]
[2,1,3]next(), next(), next()1, 2, 3In-order: [1, 2, 3]
  • The number of nodes in the tree is in the range [1, 10^5].
  • 0 <= Node.val <= 10^6
  • At most 10^5 calls will be made to hasNext and next.
  • next() and hasNext() should run in O(1) amortized and O(1) time respectively.
  • The total number of calls to next() is not more than the number of nodes.
ApproachTime: next()SpaceBest When
Stack (Lazy)O(1) amortizedO(h)Space-efficient; iterate large trees
ArrayList (Eager)O(1)O(n)Memory available; all elements needed
★ Recommended

Push all left children to stack. When popping, if right exists, push right’s left subtree.

⏱ Time O(1) amortized Each node pushed/popped once 💾 Space O(h) Stack depth = height
binary_search_tree_iterator_stack.py
from typing import Optional
# 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:
"""
Binary Search Tree Iterator using stack for in-order traversal.
Implements lazy evaluation: next() O(1) amortized, hasNext() O(1).
Space: O(h) where h is height
"""
def __init__(self, root: Optional[TreeNode]):
self.stack = []
self._push_left(root)
def _push_left(self, node):
"""Push all left nodes onto stack."""
while node:
self.stack.append(node)
node = node.left
def next(self) -> int:
"""
Return next smallest element.
Time: O(1) amortized
"""
node = self.stack.pop()
if node.right:
self._push_left(node.right)
return node.val
def hasNext(self) -> bool:
"""
Check if there are more elements.
Time: O(1)
"""
return len(self.stack) > 0
# Test cases
if __name__ == "__main__":
# Example: [7,3,15,null,null,9,20]
root = TreeNode(7)
root.left = TreeNode(3)
root.right = TreeNode(15)
root.right.left = TreeNode(9)
root.right.right = TreeNode(20)
iterator = BSTIterator(root)
result = []
while iterator.hasNext():
result.append(iterator.next())
print(result) # [3, 7, 9, 15, 20]
# Verify in-order property
print("In-order traversal correct:", result == sorted(result))
alternative

Pre-compute entire in-order traversal into an array. Iterate through array indices.

⏱ Time O(1) Direct index access 💾 Space O(n) Store all elements
binary_search_tree_iterator_arraylist.py
from typing import Optional
# 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:
"""
Binary Search Tree Iterator using pre-computed ArrayList.
Stores all in-order elements upfront.
Space: O(n), next() O(1), hasNext() O(1)
"""
def __init__(self, root: Optional[TreeNode]):
self.arr = []
self.index = 0
self._inorder(root)
def _inorder(self, node):
"""Pre-compute in-order traversal into array."""
if not node:
return
self._inorder(node.left)
self.arr.append(node.val)
self._inorder(node.right)
def next(self) -> int:
"""
Return next smallest element.
Time: O(1)
"""
val = self.arr[self.index]
self.index += 1
return val
def hasNext(self) -> bool:
"""
Check if there are more elements.
Time: O(1)
"""
return self.index < len(self.arr)
# Test cases
if __name__ == "__main__":
# Example: [7,3,15,null,null,9,20]
root = TreeNode(7)
root.left = TreeNode(3)
root.right = TreeNode(15)
root.right.left = TreeNode(9)
root.right.right = TreeNode(20)
iterator = BSTIterator(root)
result = []
while iterator.hasNext():
result.append(iterator.next())
print(result) # [3, 7, 9, 15, 20]
# Verify in-order property
print("In-order traversal correct:", result == sorted(result))
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
binary_search_tree_iterator_space_optimized.py
"""
Solution for Binary Search Tree Iterator
"""
def solve():
"""Implementation for approach 3 of Binary Search Tree Iterator"""
pass
if __name__ == "__main__":
print("Solution ready")