Binary Search Tree Iterator
Problem
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:
- The number of nodes in the tree is in the range
[1, 105]. 0 <= Node.val <= 106- At most
105calls will be made tohasNext, andnext.
Solution
/**
* 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 {
constructor(root) {
this.order = this.traverse(root);
this.index = 0;
}
traverse(root) {
if (!root) {
return [];
} else {
return [...this.traverse(root.left), root.val, ...this.traverse(root.right)];
}
}
next() {
return this.order[this.index++];
}
hasNext() {
return this.index < this.order.length;
}
}
/**
* 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()
*/
We pre-compute the inorder traversal of the tree root and store it in order. At the same time, we track the index index our iterator is currently on. For the next method, simply return order[index] and increment index for the next use. For the hasNext method, simply check if index is still in range of order.
Follow-up
Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?
Solution
/**
* 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 {
constructor(root) {
this.iterator = this.traverse(root);
this.complete = false;
this.nextVal = this.iterator.next().value;
}
* traverse(root) {
let node = root;
const stack = [];
while (stack.length || node) {
while (node) {
stack.push(node);
node = node.left;
}
node = stack.pop();
yield node.val;
node = node.right;
}
this.complete = true;
}
next() {
const val = this.nextVal;
this.nextVal = this.iterator.next().value;
return val;
}
hasNext() {
return !this.complete;
}
}
/**
* 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()
*/
We use an iterative version of DFS in combination with a generator function. More specifically, whenever we reach a terminating node in the method * traverse, we yield the value of that node. In addition, when there are no more nodes, we set the complete flag to true which is used by the method hasNext.
Since we are using DFS, the size of stack is bounded by O(h). It is also easy to see that hasNext runs in O(1) time. As for next, since each node in the tree root is pushed and popped at most once from stack, it has amortized runtime O(1).