看到这道题第一个想法是想利用BST的特性,即中序遍历打印可以得到从小到大的一个list。所以可以先new一个arraylist去按中序遍历存储所有node,然后.next()即查看arraylist的第一个节点(因为arraylist里的node就是从小到大排列好的),查看完了就把它从arraylist里remove掉。全remove了arraylist就空了,于是hasNext()即查看这个arraylist是否为空来达到目的。
public class BSTIterator {
/*
* @param root: The root of binary tree.
*/
public ArrayList<TreeNode> list;
public BSTIterator(TreeNode root) {
list = new ArrayList<TreeNode>();
inOrder(root,list);
}
public void inOrder(TreeNode root, ArrayList<TreeNode> list){
if(root == null) return;
inOrder(root.left,list);
list.add(root);
inOrder(root.right,list);
}
/*
* @return: True if there has next node, or false
*/
public boolean hasNext() {
return !list.isEmpty();
}
/*
* @return: return next node
*/
public TreeNode next() {