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();
        }
    }
    
  • 相关阅读:
    P1242 新汉诺塔(hanio)
    P2878 [USACO07JAN]保护花朵Protecting the Flowers
    P2096 最佳旅游线路
    [P1363] 幻想迷宫
    在矩阵上跑最小生成树
    tarjan+topsort
    tarjan缩点
    【P3398]】仓鼠找sugar
    树形数组暴力
    解决跨域问题
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12793791.html
Copyright © 2011-2022 走看看