Binary Search Tree Iterator
Question (LC.173)
Example
// root is the root node of BST [4,2,10,1,3,6,11]
BSTIterator iter = new BSTIterator(root);
while (iter.hasNext()) print iter.next() + ",";
// output: 1,2,3,4,6,10,11Approach
Code
public class BSTIterator {
private Stack<TreeNode> stack;
private TreeNode current;
/** Initialize the stack */
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
current = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
// we are not at the bottom right of the BST
return (!stack.isEmpty() || current != null);
}
/** @return the next smallest number */
public int next() {
int smallest;
// left child first
while (current != null) {
stack.push(current);
current = current.left;
}
// backtrack to parent
// log inorder
current = stack.pop();
smallest = current.val;
// right child last
current = current.right;
return smallest;
}
}Reading
Last updated