• 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;
        }
    }
  • 相关阅读:
    手机通讯录实现
    leetcode
    android 上手维修设备和推断启动服务
    MVC Code First (代码优先)
    10000阶乘
    telnet发电子邮件
    nodejs显现events.js:72抛出错误
    指针
    脑洞门大开思维工具:六顶思考帽
    C#实现CAD数据转shape或mdb
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5560041.html
Copyright © 2020-2023  润新知