L3-016 二叉搜索树的结构

这篇博客介绍了一种使用C++实现的二叉搜索树(BST),包括创建空节点、插入节点和查找节点的功能。代码中展示了如何根据输入值动态构建BST,并提供了查询路径、判断节点关系以及路径查找的实现。主要关注数据结构和算法的应用。

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

#include<bits/stdc++.h>
using namespace std;
typedef	struct	TreeNode *BinTree;
typedef long long ll;
map<ll,int>mp;
struct	TreeNode {
	int	data;
	BinTree	left;
	BinTree	right;
	BinTree	fa;
};
BinTree creatempty() {
	BinTree tree=(BinTree)malloc(sizeof(TreeNode));
	tree->left=NULL;
	tree->right=NULL;
	tree->fa=NULL;
	return tree;
}
void build(BinTree bt,int x) {
	if(x<bt->data) {
		if(bt->left==NULL) {
			BinTree l=creatempty();
			l->data=x;
			l->fa=bt;
			bt->left=l;
			return;
		} else {
			build(bt->left,x);
		}
	} else if(x>bt->data) {
		if(bt->right==NULL) {
			BinTree r=creatempty();
			r->data=x;
			r->fa=bt;
			bt->right=r;
			return;
		} else {
			build(bt->right,x);
		}
	}
}
int find(BinTree bt,int x,int h) {
	if(x<bt->data) return find(bt->left,x,h+1);
	if(x>bt->data) return find(bt->right,x,h+1);
	if(x==bt->data)return h;
}
BinTree finds(BinTree bt,int x) {
	if(x<bt->data)return finds(bt->left,x);
	if(x>bt->data)return finds(bt->right,x);
	if(x==bt->data)return bt;
}
int main() {
	int n,x;
	int root;
	cin>>n;
	cin>>x;
	root=x;
	mp[x]=1;
	BinTree bt=creatempty();
	bt->data=x;
	for(int i=1; i<n; i++) {
		cin>>x;
		mp[x]=1;
		build(bt,x);
	}
	int q;
	cin>>q;
	while(q--) {
		int x,y;
		cin>>x;
		string s;
		cin>>s;
		if(s[0]=='i') {
			cin>>s;
			cin>>s;
			if(s[0]=='r'&&s[1]=='o') {
				if(root==x)cout<<"Yes"<<endl;
				else cout<<"No"<<endl;
			} else if(s[0]=='p') {
				cin>>s;
				cin>>y;
				if(mp[x]&&mp[y]&&y!=root) {
					if(finds(bt,y)->fa==finds(bt,x))cout<<"Yes"<<endl;
					else cout<<"No"<<endl;
				} else {
					cout<<"No"<<endl;
				}
			} else if(s[0]=='l') {
				cin>>s;
				cin>>s;
				cin>>y;
				if(mp[x]&&mp[y]&&x!=root) {
					if(finds(bt,y)->left==finds(bt,x))cout<<"Yes"<<endl;
					else cout<<"No"<<endl;
				} else {
					cout<<"No"<<endl;
				}
			}
			else if(s[0]=='r') {
				cin>>s;
				cin>>s;
				cin>>y;
				if(mp[x]&&mp[y]&&x!=root) {
					if(finds(bt,y)->right==finds(bt,x))cout<<"Yes"<<endl;
					else cout<<"No"<<endl;
				} else {
					cout<<"No"<<endl;
				}
			}
		}
		else if(s[0]=='a'){
			cin>>y;
			cin>>s;
			cin>>s;
			if(s[0]=='s'){
				if(mp[x]&&mp[y]&&x!=root&&y!=root) {
					if(finds(bt,x)->fa==finds(bt,y)->fa)cout<<"Yes"<<endl;
					else cout<<"No"<<endl;
				} else {
					cout<<"No"<<endl;
				}
			}
			else {
				cin>>s;
				cin>>s;
				cin>>s;
				if(mp[x]&&mp[y]&&x!=root&&y!=root) {
					if(find(bt,x,1)==find(bt,y,1))cout<<"Yes"<<endl;
					else cout<<"No"<<endl;
				} else {
					cout<<"No"<<endl;
				}
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值