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;
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/85230715
今日推荐