Code & Func
2019-11-21

第17天,又是一道之前没做出来的题目,然而好像并不难啊。

今天的题目是 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:

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

Example 2:

1
Input: root = [5,3,6,2,4,null,null,1], k = 3
2
5
3
/ \
4
3 6
5
/ \
6
2 4
7
/
8
1
9
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?


题意很简单就是求BST中第k小的数字,然后BST本身就包含一定的顺序信息,利用BST中序遍历是有序的性质,我们可以很快的把这道题写出来:

1
int res;
2
int kthSmallest(TreeNode* root, int k) {
3
res = 0;
4
kthSmallestR(root, k);
5
return res;
6
}
7
bool kthSmallestR(TreeNode *root, int &k) {
8
// cout << root << endl;
9
if (root == nullptr) return false;
10
11
if (kthSmallestR(root->left, k)) return true;
12
// cout << root->val << endl;
13
if ((--k) == 0) {
14
res = root->val;
15
return true;
3 collapsed lines
16
}
17
return kthSmallestR(root->right, k);
18
}

然后我们可以写出非递归版本的:

1
int kthSmallest(TreeNode* root, int k) {
2
stack<TreeNode *> st;
3
4
while(root || !st.empty()) {
5
while(root) {
6
st.push(root);
7
root = root->left;
8
}
9
if (st.empty()) break;
10
root = st.top(); st.pop();
11
if (--k == 0) break;
12
root = root->right;
13
}
14
15
if(root) return root->val;
3 collapsed lines
16
else return -1;
17
18
}

BTW,这道题的测试有点不稳定,同一个代码会测试出不同的时间。

上一条动态