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);
    }
}
posted @ 2020-05-08 11:07  AAAmsl  阅读(49)  评论(0编辑  收藏  举报