给了一个BST的根节点,要求写一个遍历类,将这棵树从小到大遍历一遍。
我的做法是先把BST遍历一遍, 然后放到数组里,这样看起来似乎题目很简单。
public class BSTIterator {
int len = 0, index = 0;
int[] arr = new int[1000000];
public BSTIterator(TreeNode root) {
search(root);
len = index;
index = 0;
}
public void search(TreeNode f) {
if (f == null)
return;
search(f.left);
arr[index++] = f.val;
search(f.right);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if (index == len)
return false;
return true;
}
/** @return the next smallest number */
public int next() {
return arr[index++];
}
}