173 binary search tree iterator

2017-10-24  本文已影响0人  Fei_JOB
public class BSTIterator {
   Stack<TreeNode> stack;
   public BSTIterator(TreeNode root) {
       stack = new Stack<TreeNode>();
       pushThePath(stack, root);
   }
   
 
public void pushThePath(Stack st, TreeNode root){
       while(root != null){
           st.push(root);
           root = root.left;
       }
   }

   /** @return whether we have a next smallest number */
   public boolean hasNext() {
       return !stack.isEmpty();
   }

   /** @return the next smallest number */
   public int next() {
       TreeNode cur = stack.pop();
       pushThePath(stack, cur.right);
       return cur.val;
   }
}
上一篇下一篇

猜你喜欢

热点阅读