BST二叉搜索树

本文介绍了如何使用二叉搜索树(BST)结构实现查询特定数字的排名、查找排名对应的数字以及处理前驱和后继操作。主要涉及插入、查询和更新操作在BST中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

洛谷P5076 【深基16.例7】普通二叉树(简化版)

  1. 查询 �x 数的排名(排名定义为比当前数小的数的个数 +1+1。若有多个相同的数,应输出最小的排名)。
  2. 查询排名为 �x 的数。
  3. 求 �x 的前驱(前驱定义为小于 �x,且最大的数)。若未找到则输出 −2147483647−2147483647。
  4. 求 �x 的后继(后继定义为大于 �x,且最小的数)。若未找到则输出 21474836472147483647。
  5. 插入一个数 �x。

        第一行是一个整数 �q,表示操作次数。

        接下来 �q 行,每行两个整数 ��,�op,x,分别表示操作序号以及操作的参数 �x。

BST模板?

#include<bits/stdc++.h>//万能头文件
using namespace std;   //命名空间
int cnt = 1;
struct node{
	int left, right; //左右子树
	int value;	//节点存的值
	int num;	//重复值有多少个
	int size;	//左右子树及自己的节点和 
}t[10005];
void insert(int x, int root){
	if(cnt == 1){
		node tmp = {0,0,x,1,1};
		t[cnt] = tmp;
		cnt++;
	}else{
		if(x < t[root].value){
			if(t[root].left == 0){
				node tmp = {0,0,x,1,1};
				t[cnt] = tmp;
				t[root].left = cnt;
				cnt++;
			}else insert(x, t[root].left);
		}
		if(x == t[root].value) t[root].num++; 
		if(x > t[root].value){
			if(t[root].right == 0){
				node tmp = {0,0,x,1,1};
				t[cnt] = tmp;
				t[root].right = cnt;
				cnt++;
			}else insert(x, t[root].right);
		}
	}
	t[root].size = t[t[root].left].size + t[t[root].right].size + t[root].num;
}
int query1(int x, int root){ //查找数字x的排名 
	if(root == 0) return 1;
	if(x < t[root].value) return query1(x,t[root].left);
	if(x == t[root].value) return t[t[root].left].size + 1;
	if(x > t[root].value) return t[t[root].left].size + t[root].num + query1(x,t[root].right);
}
int query2(int x, int root){ //查找排名为x的数字是什么 
	if(x <= t[t[root].left].size) return query2(x,t[root].left);
	if(x <= t[t[root].left].size + t[root].num) return t[root].value;
	return query2(x-t[t[root].left].size-t[root].num, t[root].right);
}
int main(){
	int n, op, x;
	cin >> n;
	for(int i = 0; i < n; i++){
		cin >> op >> x;
		if(op == 1) cout << query1(x,1) << endl;
		if(op == 2) cout << query2(x,1) << endl;
		if(op == 3){
			int tmp = query1(x,1);
			if(tmp == 1) cout << -2147483647 << endl;
			else cout << query2(tmp - 1, 1) << endl;
		}
		if(op == 4){
			int tmp = query1(x + 1,1);
			if(tmp == cnt) cout << 2147483647 << endl;
			else cout << query2(tmp, 1) << endl;
		}
		if(op == 5) insert(x,1);
	}
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值