zoukankan      html  css  js  c++  java
  • 173. Binary Search Tree Iterator

    /*
     * 173. Binary Search Tree Iterator 
     * 2016-6-4 by Mingyang
     * 就是一个典型的DFS,保证在constructor的时候就需要保持一个stack的情况,push进去最小的那个值
     * 每次取了值以后注意不要忘了继续往stack里面push
     * return the next smallest number in the BST是值的是从零开始起return,一个一个的return
     */
    class BSTIterator {
        Stack<TreeNode> stack;
        public BSTIterator(TreeNode root) {
            stack = new Stack<TreeNode>();
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
        }
        public boolean hasNext() {
            return !stack.isEmpty();
        }
        public int next() {
            TreeNode node = stack.pop();
            int result = node.val;
            if (node.right != null) {
                node = node.right;
                while (node != null) {
                    stack.push(node);
                    node = node.left;
                }
            }
            return result;
        }
    }
    //下面就是自己写的一次过的代码,多用了一个queue,一次性的把所有的都存起来了,一个一个取方便
     class BSTIterator1 {
        Stack<TreeNode> stack=new Stack<TreeNode>();
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        public BSTIterator1(TreeNode root) {
            TreeNode p=root;
            while(p!=null||stack.size()!=0){
                if(p!=null){
                    stack.push(p);
                    p=p.left;
                }else{
                    TreeNode q=stack.pop();
                    queue.add(q);
                    p=q.right;
                }
            }
        }
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            if(queue.size()>0)
              return true;
            else
              return false;
        }
        /** @return the next smallest number */
        public int next() {
            return queue.remove().val;
        }
    }
  • 相关阅读:
    Mathematica 计算矩阵的伴随矩阵
    教你如何在word中像LaTex那样打出漂亮的数学公式
    中国科学院大学2016年硕转博考试试题
    161024解答
    161023解答
    161020-1解答
    关于查询扩展版ESI高被引论文的说明
    [Tex学习笔记]让项目编号从4开始
    [Tex学习]WinEdit 常用软件快捷键
    最著名的数学家一般也是最著名的力学家
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5560041.html
Copyright © 2011-2022 走看看