BST 的中序遍历结果是有序的,因此第
题目
给定一棵由
输入格式
- 第一行一个整数
,表示 BST 的节点数; - 第二行
个整数,按插入顺序构建 BST; - 第三行一个整数
,表示查询次数; - 接下来
行,每行一个整数 。
输出格式
- 对于每个查询,输出一行一个整数,表示第
小的元素。
样例
样例输入
input
7
50 30 70 20 40 60 80
5
1
3
5
7
4样例输出
output
20
40
60
80
50样例解释
BST 的中序遍历序列为:
- 第
小: - 第
小: - 第
小: - 第
小: - 第
小:
题解
点击查看题解
核心思路
利用 BST 中序遍历的有序性,可以在遍历过程中计数:
- 对 BST 进行中序遍历(左-根-右);
- 维护一个计数器
cnt,每访问一个节点cnt++; - 当
cnt == k时,当前节点即为答案。
单次查询时间复杂度
复杂度分析
- 时间复杂度:单次查询
, 次查询共 最坏; - 空间复杂度:
递归栈空间。
点击查看参考代码
cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
TreeNode* insert(TreeNode* root, int x) {
if (!root) return new TreeNode(x);
if (x < root->val) root->left = insert(root->left, x);
else root->right = insert(root->right, x);
return root;
}
int kthSmallest(TreeNode* root, int k, int& cnt) {
if (!root) return -1;
int left = kthSmallest(root->left, k, cnt);
if (left != -1) return left;
if (++cnt == k) return root->val;
return kthSmallest(root->right, k, cnt);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
TreeNode* root = nullptr;
for (int i = 0; i < n; ++i) {
int x; cin >> x;
root = insert(root, x);
}
int q;
cin >> q;
while (q--) {
int k;
cin >> k;
int cnt = 0;
cout << kthSmallest(root, k, cnt) << '\n';
}
return 0;
}本地运行与提交
powershell
pnpm lab:run -- labs/chapter-05/exercise/E-05-04-bst-kth-smallest