1. 程式人生 > >LeetCode刷題Medium篇Kth Smallest Element in a BST

LeetCode刷題Medium篇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.

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3

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?

 

十分鐘嘗試

類似於陣列尋找第k大的數,先判斷k大的數字位於左半區間還是右半區間。然後遞迴尋找。其實就是折半查詢。

注意,折半查詢應用的條件是陣列有序。此處二叉樹也是有序的,所以可以利用。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    private int count(TreeNode root){
       if(root==null){
            return 0;
        }
        return 1+count(root.left)+count(root.right);
        
    }
    
    public int kthSmallest(TreeNode root, int k) {
        //類似於陣列尋找第k大的數,先判斷第k大數字在左側還是右側,記得考慮根節點
        if(root==null){
            return 0;
        }
        //計算左側,也就是比根小的元素個數,判斷k大位置區間
        int count=count(root.left);
        if(k<count+1){
           return  kthSmallest(root.left,k);
        }
        if(k>count+1){
           return  kthSmallest(root.right,k-count-1);
        }
         return root.val;
    }
}