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.
想了半天没想出来这道题的考点,是考全局变量吗?还是考BST中序遍历是递增序列?
中序遍历了一遍直接判断竟然就A了,连测试集都木有构建,真是史上前所未有。。
再回顾一下BST吧。小的值在左子树,大的数在右子树。这样的结构很容易拿到最值,即最左边的节点是最小的,最右节点是最大值。中序遍历可以得到一个ordered list。
上代码吧~
public class BSTIterator {
ArrayList<Integer> orderedList = new ArrayList<Integer>();
int index,length;
public void MiddleOrder(TreeNode root){
if(root != null){
MiddleOrder(root.left);
orderedList.add(root.val);
MiddleOrder(root.right);
}
}
public BSTIterator(TreeNode root) {
MiddleOrder(root);
index = 0;
length = orderedList.size();
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(index < length){
index++;
return true;
}
return false;
}
/** @return the next smallest number */
public int next() {
return orderedList.get(index - 1);
}
}
61 / 61 test cases passed.
Status: Accepted
Runtime: 404 ms