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<Integer> count = new ArrayList<>();
        helper(root, count);
        return count.get(k-1);
    }
    
    
    public void helper(TreeNode node, List<Integer>count){
        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);
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容