• 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();
        }
    }
    
  • 相关阅读:
    linux中nc命令
    Centos6.5 安装zabbix3(收藏,非原创)
    紀念
    算法学习资源收集
    一道奇怪的求和题
    P5717 题解
    P1424 刷题记录
    P1888 题解
    P1422 刷题记录
    P1055 题解
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12793791.html
Copyright © 2020-2023  润新知