zoukankan      html  css  js  c++  java
  • LeetCode 230: Kth Smallest Element in a BST

    /**
     * 230. Kth Smallest Element in a BST
     * 1. Time:O(n)  Space:O(n)
     * 2. Time:O(h+k)  Space:O(h+k)
     * 3. Time:O(h+k)  Space:O(h+k)
     */
    
    // 1. Time:O(n)  Space:O(n)
    class Solution {
        public int kthSmallest(TreeNode root, int k) {
            List<Integer> res = new ArrayList<>();
            helper(root,res);
            return res.get(k-1);
        }
        
        private void helper(TreeNode root, List<Integer> res){
            if(root==null) return;
            helper(root.left,res);
            res.add(root.val);
            helper(root.right,res);
        }
    }
    
    // 2. Time:O(h+k)  Space:O(h+k)
    class Solution {
        public int kthSmallest(TreeNode root, int k) {
            Stack<TreeNode> stack = new Stack<>();
            while(true){
                while(root!=null){
                    stack.push(root);
                    root=root.left;
                }
                root = stack.pop();
                if(--k == 0) return root.val;
                root = root.right;
            }
        }
    }
    
    // 3. Time:O(h+k)  Space:O(h+k)
    class Solution {
        
        private int cnt=0;
        private int res;
        
        public int kthSmallest(TreeNode root, int k) {
            helper(root,k);
            return res;
        }
        
        private void helper(TreeNode root, int k){
            if(root==null) return;
            helper(root.left,k);
            if(++cnt == k){
                res = root.val;
            }
            helper(root.right,k);
        }
    }
    
  • 相关阅读:
    bind函数
    尾置返回类型
    lambda表达式
    C++谓词
    capacity和size
    容器操作可能会使迭代器失效
    特殊的forward_list操作
    向顺序容器添加元素
    swap与assign
    迭代器
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12849301.html
Copyright © 2011-2022 走看看