美文网首页
173 binary search tree iterator

173 binary search tree iterator

作者: Fei_JOB | 来源:发表于2017-10-24 02:46 被阅读0次
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;
   }
}

相关文章

网友评论

      本文标题:173 binary search tree iterator

      本文链接:https://www.haomeiwen.com/subject/zrizuxtx.html