[leetcode] 230. Kth Smallest Element in a BST 解题报告

题目链接:https://leetcode.com/problems/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?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).

思路:要找第k个数,可以统计到当前结点左边有多少结点,

1.如果左边的结点数加上当前这个结点个数正好等于k,则说明这就是第k个数

2.如果左边结点数加当前结点个数小于k,则要往右结点去找第k个数

3.如果左边结点数加当前结点个数大于k,则要往左子树去找第k个数

这种时间复杂度应该是O(n),因为最坏情况可能要统计到每一个结点。

如果要频繁查找的话可以在数据结构中添加一个字段,记录左节点有多少个。这样最多只要O(h)的时间复杂度。

代码如下:

/**
 * 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 count(TreeNode* root)
    {
        if(!root) return 0;
        return 1 + count(root->left) + count(root->right);
    }
    int search(TreeNode* root, int k, int sum)
    {
        int cnt = count(root->left) + 1 + sum; 
        if(cnt == k) return root->val;
        else if(cnt > k) 
            return search(root->left, k, sum);
        else
            return search(root->right, k, cnt);
    }
    int kthSmallest(TreeNode* root, int k) {
        return search(root, k, 0);
    }
};


你可能感兴趣的:(LeetCode,tree,binary)