230. Kth Smallest Element in a BST

problem description

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?

algorithm thought

得到第k个数,这里其实可以利用之前得到数组中k大的数的解法。只是之前那个是要用O(n)时间将第k个数归位,这里是用O(n)时间得到当前root是第几大的数。对于BST来说,只要得到左子节点位置即可

code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        while(true){
            int number=count(root->left);
            if(number+1==k){
                return root->val;
            }else if(number+1<k){
                k-=(number+1);
                root=root->right;
            }else{
                root=root->left;
            }
        }
        return 0;
    }
    int count(TreeNode* root){
        if(root==NULL)
            return 0;
        return 1+count(root->left)+count(root->right);
    }
};

algorithm analysis

最坏情况下时间复杂度还是需要O(n)时间。

Last updated