# 【CCCC】L3-016 二叉搜索树的结构 (30分)，，手动建堆（二叉搜索树节点询问）,map写法

#### problem

L3-016 二叉搜索树的结构 (30分)

A is the root，即"A是树的根"；
A and B are siblings，即"A和B是兄弟结点"；
A is the parent of B，即"A是B的双亲结点"；
A is the left child of B，即"A是B的左孩子"；
A is the right child of B，即"A是B的右孩子"；
A and B are on the same level，即"A和B在同一层上"。

5
2 4 1 3 0
8
2 is the root
1 and 4 are siblings
3 and 0 are on the same level
2 is the parent of 4
3 is the left child of 4
1 is the right child of 2
4 and 0 are on the same level
100 is the right child of 3

Yes
Yes
Yes
Yes
Yes
No
No
No

• 给出n个数，建立二叉搜索树
• m个询问，判断两个节点之间的关系（双亲，兄弟，孩子）

#### solution

• 开个结构把每个点的l,r,fa,h都存下来，记得初始化-1.
• 用map映射代替数组映射建树，方便查找有没有这个节点。
#include<bits/stdc++.h>
using namespace std;

struct node{int l=-1, r=-1, fa=-1, h;};
map<int,node>Tree;
void insert(int u, int h, int v){
if(u==-1)return ;
int uu = (v<u ? Tree[u].l : Tree[u].r);
if(uu!=-1){
insert(uu,h+1,v);
}else{
if(v<u)Tree[u].l = v;
else Tree[u].r = v;
Tree[v].fa = u;
Tree[v].h = h;
}
}

bool judge(int u, int a, int b, string lk){
if(lk=="root")return u==a;;
if(Tree.find(a)==Tree.end() || Tree.find(b)==Tree.end())return false;
if(lk=="siblings")return Tree[a].fa==Tree[b].fa;
if(lk=="parent")return Tree[a].l==b || Tree[a].r==b;
if(lk=="left")return Tree[b].l == a;
if(lk=="right")return Tree[b].r == a;
if(lk=="level")return Tree[a].h==Tree[b].h;
}

int main(){
int n, rt, t;
cin>>n>>rt; //rt是根
for(int i = 2; i <= n; i++){
cin>>t;
insert(rt,1,t);
}
int m, a=0, b=0;  cin>>m;
for(int i = 1; i <= m; i++){
string s, lk;  cin>>a>>s;
if(s=="and"){
cin>>b>>s>>s;
if(s=="siblings")lk = s;
else cin>>s>>s>>lk;
}else{
cin>>s>>lk;
if(lk=="parent")cin>>s>>b;
else if(lk!="root")cin>>s>>s>>b;
}
if(judge(rt,a,b,lk))cout<<"Yes\n";
else cout<<"No\n";
}
return 0;
}



11-13 1861
12-08 427

03-26 335
03-26 385
05-17 3640
04-24 1083
03-23 548
03-28 181
03-27 415
05-30 325
10-09 53
03-15 155
03-22 193
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客