173 binary search tree iterator

public class BSTIterator {
   Stack stack;
   public BSTIterator(TreeNode root) {
       stack = new Stack();
       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;
   }
}

你可能感兴趣的:(173 binary search tree iterator)