这题有很多解法。
解法1. 根据BST的中序遍历是非递减序列这个性质。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the given BST
* @param k: the given k
* @return: the kth smallest element in BST
*/
int kthSmallest(TreeNode * root, int k) {
vector<int> inOrderList;
inOrderTraversal(root, inOrderList);
return inOrderList[k-1];
}
void inOrderTraversal(TreeNode *root, vector<int> &inOrderList) {
if (!root)
return;
inOrderTraversal(root->left, inOrderList);
inOrderList.push_back(root->val);
inOrderTraversal(root->right, inOrderList);
}
};
上面代码的时间复杂度是O(n), 最好最坏都是。空间复杂度都是O(n)。
解法2:
BST In-order Traversal的非递归版
有个好处就是可以用个counter来计数。
用 stack,从第一个点开始,走 k-1 步,就是第 k 个点了。
时间复杂度是 O(h + k) h 是树的高度。可以理解成一开始先要走到最左边最下面的节点,这里要耗费O(h),然后再从这个节点开始,又需要走O(k)步,所以是O(h+k)。
下次实践。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the given BST
* @param k: the given k
* @return: the kth smallest element in BST
*/
int kthSmallest(TreeNode *root, int k) {
stack<TreeNode *> stk;
int count = 0;
while (root || !stk.empty()) {
while(root) {
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
count++;
if (count == k) {
return root->val;
}
root = root->right;
}
}
};
解法3:Quick-Select。
详见
https://www.jiuzhang.com/solution/kth-smallest-element-in-a-bst/#tag-highlight
下次实践。
Challenge
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?
答案是用QuickSelect方法做预处理,把每个BST节点的子树的节点个数记录下来,可以在建树的时候一起完成。下次实践一下。