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

    /**
     * 173. Binary Search Tree Iterator
     * 1. Time:O()  Space:O()
     * 2. Time:O()  Space:O()
     */
    
    // 1. Time:O()  Space:O()
    class BSTIterator {
    
        ArrayList<Integer> res;
        int index;
        
        public BSTIterator(TreeNode root) {
            this.res = new ArrayList<>();
            this.index = -1;
            this.inOrder(root);
        }
        
        private void inOrder(TreeNode root){
            if(root==null) return;
            inOrder(root.left);
            res.add(root.val);
            inOrder(root.right);
        }
        
        /** @return the next smallest number */
        public int next() {
            return this.res.get(++index);
        }
        
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return this.index+1<this.res.size();
        }
    }
    
    // 2. Time:O()  Space:O()
    class BSTIterator {
        
        private Stack<TreeNode> stack;
    
        public BSTIterator(TreeNode root) {
            stack = new Stack<>();
            while(root!=null){
                stack.push(root);
                root = root.left;
            }
        }
        
        /** @return the next smallest number */
        public int next() {
            TreeNode node = stack.pop();
            TreeNode tmp = node.right;
            while(tmp!=null){
                stack.push(tmp);
                tmp = tmp.left;
            }
            return node.val;
        }
        
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !stack.isEmpty();
        }
    }
    
  • 相关阅读:
    第03组 Beta冲刺(4/5)
    第03组 Beta冲刺(3/5)
    第03组 Beta冲刺(2/5)
    第03组 Beta冲刺(1/5)
    第03组 Alpha冲刺(6/6)
    第03组 Alpha冲刺(5/6)
    软工实践个人总结
    最终作业
    Beta答辩总结
    Beta 冲刺(7/7)
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12793791.html
Copyright © 2011-2022 走看看