173. Binary Search Tree Iterator - Explanation
Description
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root)Initializes an object of theBSTIteratorclass. Therootof the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.boolean hasNext()Returnstrueif there exists a number in the traversal to the right of the pointer, otherwise returnsfalse.int next()Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Example 1:
Input: ["BSTIterator","next","next","hasNext","next","hasNext","next","hasNext","next","hasNext"], [[[7,3,15,null,null,9,20]],[],[],[],[],[],[],[],[],[]]
Output: [null,3,7,true,9,true,15,true,20,false]Explanation:
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
Constraints:
1 <= The number of nodes in the tree <= 100,000.0 <= Node.val <= 1,000,000- At most
100,000calls will be made tohasNext, andnext.
Follow up:
- Could you implement
next()andhasNext()to run in averageO(1)time and useO(h)memory, wherehis the height of the tree?
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Binary Search Tree Properties - Understanding that inorder traversal yields sorted elements
- Inorder Tree Traversal - Both recursive and iterative implementations
- Stack Data Structure - Used to simulate recursion for space-efficient iterative traversal
1. Flattening the BST (DFS)
Intuition
The simplest approach is to perform an inorder traversal of the BST upfront and store all values in an array. Since inorder traversal of a BST visits nodes in ascending order, the array will be sorted. Then, next() simply returns the next element from the array, and hasNext() checks if there are more elements remaining.
Algorithm
- In the constructor, perform a recursive inorder DFS traversal of the tree.
- Store each visited node's value in an array.
- Maintain an iterator pointer starting at index
0. - For
next(), return the value at the current pointer and increment it. - For
hasNext(), check if the pointer is less than the array length.
# 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.arr = []
self.itr = 0
def dfs(node):
if not node:
return
dfs(node.left)
self.arr.append(node.val)
dfs(node.right)
dfs(root)
def next(self) -> int:
val = self.arr[self.itr]
self.itr += 1
return val
def hasNext(self) -> bool:
return self.itr < len(self.arr)Time & Space Complexity
- Time complexity:
- time for initialization.
- time for each and function calls.
- Space complexity:
2. Flatten the BST (Iterative DFS)
Intuition
This is the same approach as the recursive version, but implemented iteratively using an explicit stack. We simulate the recursion by pushing nodes onto the stack, going left as far as possible, then processing nodes and going right. The result is the same sorted array of values.
Algorithm
- In the constructor, use a stack to perform iterative inorder traversal.
- Push nodes onto the stack while going left, then pop and add to the array, then go right.
- Store all values in an array and maintain an iterator pointer.
- For
next(), return the value at the current pointer and increment it. - For
hasNext(), check if the pointer is less than the array length.
# 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.arr = []
self.itr = 0
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
self.arr.append(root.val)
root = root.right
def next(self) -> int:
val = self.arr[self.itr]
self.itr += 1
return val
def hasNext(self) -> bool:
return self.itr < len(self.arr)Time & Space Complexity
- Time complexity:
- time for initialization.
- time for each and function calls.
- Space complexity:
3. Iterative DFS - I
Intuition
Instead of flattening the entire tree upfront, we can save memory by only keeping track of the path from the root to the current position. We initialize the stack with all nodes along the leftmost path. When next() is called, we pop the top node, and if it has a right child, we push all nodes along the leftmost path of the right subtree. This way, the stack always contains the ancestors needed to continue the traversal.
Algorithm
- In the constructor, push all nodes from root to the leftmost leaf onto the stack.
- For
next(), pop the top node from the stack as the result. - If the popped node has a right child, push all nodes from the right child down to its leftmost descendant.
- Return the popped node's value.
- For
hasNext(), return true if the stack is not empty.
# 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 = []
while root:
self.stack.append(root)
root = root.left
def next(self) -> int:
res = self.stack.pop()
cur = res.right
while cur:
self.stack.append(cur)
cur = cur.left
return res.val
def hasNext(self) -> bool:
return bool(self.stack)Time & Space Complexity
- Time complexity: in average for each function call.
- Space complexity:
Where is the number of nodes and is the height of the given tree.
4. Iterative DFS - II
Intuition
This is a slight variation of the previous approach. Instead of initializing the stack in the constructor, we defer the leftward traversal to the next() method. We keep a pointer to the current node and only push nodes onto the stack when next() is called. This makes the constructor O(1) but the logic is essentially the same.
Algorithm
- In the constructor, store the root as the current node and initialize an empty stack.
- For
next(), push all nodes from the current node down to its leftmost descendant onto the stack. - Pop the top node from the stack, set the current node to its right child.
- Return the popped node's value.
- For
hasNext(), return true if either the current node is not null or the stack is not empty.
# 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.cur = root
self.stack = []
def next(self) -> int:
while self.cur:
self.stack.append(self.cur)
self.cur = self.cur.left
node = self.stack.pop()
self.cur = node.right
return node.val
def hasNext(self) -> bool:
return bool(self.cur) or bool(self.stack)Time & Space Complexity
- Time complexity: in average for each function call.
- Space complexity:
Where is the number of nodes and is the height of the given tree.
Common Pitfalls
Using Preorder or Postorder Instead of Inorder
BST iterator must return elements in ascending order, which requires inorder traversal (left, root, right). Using preorder or postorder traversal produces elements in the wrong order.
Forgetting to Traverse the Right Subtree After Popping
When using the stack-based approach, after popping a node and returning its value, you must push the leftmost path of its right subtree onto the stack. Forgetting this step causes right subtrees to be skipped entirely.
# Wrong: just pop and return
node = stack.pop()
return node.val
# Correct: also handle right subtree
node = stack.pop()
cur = node.right
while cur:
stack.append(cur)
cur = cur.left
return node.valIncorrect hasNext() Implementation
The hasNext() method must return True if there are more elements to iterate. For the stack-based approach, this means checking if either the stack is non-empty OR the current pointer is not null (depending on the implementation variant).
Sign in to join the discussion