Saturday, May 5, 2012

In-order Iterator of a Binary Search Tree

[Question]
Implement an in-order iterator of Binary Search Tree (BST)

[Analysis]
Use a stack to traverse BST. The top of the stack is the element whose value has not been visited by in-order:  the next is either the left most node from this node or itself when all left sub-tree has been visited.

[Solution]
/*
 * public class BSTNode {
 *  BSTNode left, right;
 * int     value;
 * }
 */

import java.util.*;

public class BSTIterator {
BSTNode root;
Stack<BSTNode>   st;
BSTNode last;

public BSTIterator( BSTNode root ){
this.root = root;
st = new Stack<BSTNode>();
if (root!=null)
st.push(root);
last = null;
}

public boolean hasNext() {
return (!st.isEmpty());
}

public BSTNode next() {
while (last==null && st.peek().left!= null ||
last!=null && st.peek().left!= null && st.peek().left.value > last.value) {
st.push(st.peek().left);
}

last = st.pop();
if (last.right!=null) st.push(last.right);

return last;
}
}

No comments:

Post a Comment