Example
For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]
10
/ \
1 11
\ \
6 12
public class BSTIterator {
//@param root: The root of binary tree.
Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
while(root != null) {
stack.push(root);
root = root.left;
}
}
//@return: True if there has next node, or false
public boolean hasNext() {
return !stack.isEmpty();
}
//@return: return next node
public TreeNode next() {
TreeNode res = stack.pop();
TreeNode tmp = null;
if((tmp = res.right) != null) {
while(tmp != null) {
stack.push(tmp);
tmp = tmp.left;
}
}
return res;
}
}