230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ? k ? BST's total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

一刷
题解:
第一种方法,先算出左子树的node数目,判断是否在左子树内,然后通过判断进入左右递归。

public int kthSmallest(TreeNode root, int k) {
        int count = countNodes(root.left);
        if (k <= count) {
            return kthSmallest(root.left, k);
        } else if (k > count + 1) {
            return kthSmallest(root.right, k-1-count); // 1 is counted as current node
        }
        
        return root.val;
    }
    
    public int countNodes(TreeNode n) {
        if (n == null) return 0;
        
        return 1 + countNodes(n.left) + countNodes(n.right);
    }

第二种方法:
可以很明显的看到,上一种方法中,有太多的重复计算,思考,我们可以用in-order遍历将这个数组存起来(从小到大),然后输出第k个

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    public int kthSmallest(TreeNode root, int k) {
        List count = new ArrayList<>();
        helper(root, count);
        return count.get(k-1);
    }
    
    
    public void helper(TreeNode node, Listcount){
        if(node == null) return;
        if(count.size() == k) return;
        helper(node.left, count);
        count.add(node.val);
        helper(node.right, count);
    }
}

三刷
速度太慢。方法同上。但是只记录第k个值。所以不需要用arraylist

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int val;
    private int cnt;

    public int kthSmallest(TreeNode root, int k) {
        val = 0;
        cnt = 0;
        dfs(root, k);
        return val;
    }
    
    private void inorder(TreeNode root, int k) {
        if (root == null) {
            return;
        }
        inorder(root.left, k);
        if (cnt == k) {
            return;
        }
        val = root.val;
        cnt++;
        inorder(root.right, k);
    }
}

你可能感兴趣的:(230. Kth Smallest Element in a BST)