LeetCode kth-smallest-element-in-a-bst

给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

说明: 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。 示例 1:

输入: root = [3,1,4,null,2], k = 1 3 /
1 4
2 输出: 1

示例 2:

输入: root = [5,3,6,2,4,null,null,1], k = 3 5 /
3 6 /
2 4 / 1 输出: 3

进阶: 如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?

解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* 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) {
priority_queue<int, vector<int>> Q;
queue<TreeNode*> q;
q.push(root);

while (!q.empty()) {
TreeNode* tmp = q.front();
if (Q.size() < k) Q.push(tmp->val);
else if (Q.top() > tmp->val) {
Q.pop();
Q.push(tmp->val);
}
if (tmp->left) q.push(tmp->left);
if (tmp->right) q.push(tmp->right);
q.pop();
}
return Q.top();
}

int kthSmallest(TreeNode* root, int k) {
vector<int> res;
stack<TreeNode*> sta;
TreeNode *p = root;
while (p || !sta.empty()){
while(p) {
sta.push(p);
p = p->left;
}
if (!sta.empty()) {
p = sta.top();
sta.pop();
res.push_back(p->val);
p = p->right;
}
}
return res[k-1];
}

int kthSmallest(TreeNode* root, int k) {
if (!root) {
return 0;
}
int n = childNum(root->left);
if (n + 1 == k) {
return root->val;
} else if (k <= n) {
return kthSmallest(root->left, k);
} else {
return kthSmallest(root->right, k - n - 1);
}
}

int childNum(TreeNode *root) {
if (!root) {
return 0;
}
return childNum(root->left) + childNum(root->right) + 1;
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×