跳到正文

个人记录

题解 U674225 二叉搜索树

guangzhou_even约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年4月1日
收录
2026年4月2日
更新
2026年11月16日
篇幅
约 5 分钟

版本

  1. v5当前
  2. v4
  3. v3
  4. v2
更早的 1 个版本
  1. v1

U674225 二叉搜索树 题解

题意简述

依次插入 nn 个数到二叉搜索树(BST)中,每次插入后输出当前元素在树中的排名(即树中 ≤\le 当前元素的元素个数)。

解题思路

维护一个标准的二叉搜索树,每个节点存储:

  • val:节点值
  • sz:子树大小
  • L、R:左右子节点下标

插入时按 BST 规则递归,同时更新 sz。

排名计算: 要查询值 yy 的排名,从根开始:

  • 若当前节点值 ≥y\ge y,则去左子树找
  • 否则,答案加上左子树大小 + 1,再去右子树找

最终返回的数值即为排名。

时间复杂度 O(nlog⁡n)O(n \log n),空间复杂度 O(n)O(n)。

代码实现

C++
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;

struct Node {
	i64 val = 0, sz = 0, L = 0, R = 0;
};

struct BST {
	vector<Node> a;
	i64 sz(i64 x) {
		return x ? a[x].sz : 0;
	}
	i64 create(i64 x) {
		Node nd;
		nd.val = x, nd.sz = 1;
		a.push_back(nd);
		return (i64)a.size() - 1;
	}
	i64 insert(i64 x, i64 y) {
		if (!x) return create(y);
		if (a[x].val < y) {
			a[x].R = insert(a[x].R, y);
			a[x].sz = 1 + sz(a[x].L) + sz(a[x].R);
		} else {
			a[x].L = insert(a[x].L, y);
			a[x].sz = 1 + sz(a[x].L) + sz(a[x].R);
		}
		return x;
	}
	i64 rank(i64 x, i64 y) {
		if (!x) return 1;
		if (a[x].val >= y) return rank(a[x].L, y);
		return sz(a[x].L) + 1 + rank(a[x].R, y);
	}
	void init(i64 n = 0) {
		a.reserve(n + 5);
		a.push_back({0});
	}
};

int main() {
	ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
	BST bst;
	bst.init();
	i64 n, root = 0;
	cin >> n;
	for (i64 i = 0; i < n; i++) {
		i64 x;
		cin >> x;
		root = bst.insert(root, x);
		i64 r = bst.rank(root, x);
		cout << r << " \n"[i == n - 1];
	}
	return 0;
}

更多代码

此题来源于信奥书籍,书内有不太正确的代码,我在此进行了修改。

在这个程序中,我们插入新节点时,如果新节点的值小于或等于当前节点的值,我们在左子树中插入,然后返回插入后的排名;如果新节点的值大于当前节点的值,我们在右子树中插入,然后返回插入后的排名再加上左子树的大小和 11。这是因为新节点的值大于当前节点和其左子树中的所有节点,所以其排名需要加上左子树的大小和 11。

C++
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
const i64 maxn = 7e8;

struct Node {
	i64 key, size, left, right;
} node[maxn];
i64 tot = 0, root = 0;
i64 createNode(i64 key) {
	node[++tot].key = key;
	node[tot].size = 1;
	node[tot].left = node[tot].right = 0;
	return tot;
}
void update(i64 x) {
	node[x].size = node[node[x].left].size + node[node[x].right].size + 1;
}
i64 insert(i64 &x, i64 &key) {
	if (!x) {
		x = createNode(key);
		return 1;
	}
	i64 rank;
	if (node[x].key < key) {
		rank = insert(node[x].right, key) + node[node[x].left].size + 1;
	} else {
		rank = insert(node[x].left, key);
	}
	update(x);
	return rank;
}
int main() {
	ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
	i64 n;
	cin >> n;
	for (i64 i = 0; i < n; i++) {
		i64 x;
		cin >> x;
		cout << insert(root, x) << " ";
	}
	return 0;
}
原文