Binary Search Tree Iterator

Problem Statement

deeksha sharma
Algorithm Problems
1 min readJan 19, 2016

--

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.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Approach

  • Push all the left nodes to the stack starting from the root in the constructor. This will push the nodes in descending order.
  • In the hasNext() return true if the stack has elements and false if its empty
  • In the next(), pop the node from the stack, push to the stack the right subtree of this node and return its value.

Run Time Complexity

hasNext(): O(1)

next(): O(logn)

memory: O(logn)

Code

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode next;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
pushToLeft(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext(){
if(stack.empty()){
return false;
}return true;
}
/** @return the next smallest number */
public int next(){
TreeNode node = stack.pop();
pushToLeft(node.right);
return node.val;
}

private void pushToLeft(TreeNode node){
if (node != null){
stack.push(node);
pushToLeft(node.left);
}
}
}/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/

--

--

deeksha sharma
Algorithm Problems

Work for https://bonsaiilabs.com/ life long learner ,investing time heavily in personal finance, education, tech and design skills. Twitter: @deekshasharma25