https://oj.leetcode.com/problems/binary-search-tree-iterator/
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.
public BSTIterator(TreeNode root) {
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
}
/** @return the next smallest number */
public int next() {
}
从小到大的顺序输出一个Bst,可行的做法就是in-order traversal。可是一般递归的in order traversal是做不到iterator的效果的,只有循环iteration的in order traversal才可以。结合 Binary Tree Preorder Traversal 提到的循环递归树的做法,首先我们给出一个in-order traversal 循环的代码
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<Integer>();
Stack<TreeNode> tree_stack = new Stack<TreeNode>();
TreeNode tmp = root;
while(tmp != null || !tree_stack.isEmpty()){
if(tmp != null){
tree_stack.push(tmp);
tmp = tmp.left;
}else{
tmp = tree_stack.pop();
<pre name="code" class="java"> res.add(tmp.val);
tmp = tmp.right; } } return res; }
跟preorder不同的就是把输出的位置从if放到else里了。
根据这一段代码,其实这个iterator就很好写了。给出代码如下:
Stack<TreeNode> dfs_stack;
TreeNode cur;
public BSTIterator(TreeNode root) {
dfs_stack = new Stack<TreeNode>();
cur = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return cur != null || !dfs_stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
int res = 0;
while(cur != null || !dfs_stack.isEmpty()){
if(cur != null){
dfs_stack.add(cur);
cur = cur.left;
}else{
cur = dfs_stack.pop();
res = cur.val;
cur = cur.right;
break;
}
}
return res;
}
顺便说一下,如果这个是要求Preorder的iterator的话,hasNext的条件就需要做一下调整。因为这个时候即使dfs_stack非空,但实际上还是有可能已经遍历完了。最后栈里面可能都是要往上循环的parent节点