二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉搜索树。(摘自百度百科)
给定一系列互不相等的整数,将它们顺次插入一棵初始为空的二叉搜索树,然后对结果树的结构进行描述。你需要能判断给定的描述是否正确。例如将{ 2 4 1 3 0 }插入后,得到一棵二叉搜索树,则陈述句如“2是树的根”、“1和4是兄弟结点”、“3和0在同一层上”(指自顶向下的深度相同)、“2是4的双亲结点”、“3是4的左孩子”都是正确的;而“4是2的左孩子”、“1和3是兄弟结点”都是不正确的。
输入格式:
输入在第一行给出一个正整数N(≤100),随后一行给出N个互不相同的整数,数字间以空格分隔,要求将之顺次插入一棵初始为空的二叉搜索树。之后给出一个正整数M(≤100),随后M行,每行给出一句待判断的陈述句。陈述句有以下6种:
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
在同一层上"。
题目保证所有给定的整数都在整型范围内。
输出格式:
对每句陈述,如果正确则输出Yes
,否则输出No
,每句占一行。
输入样例:
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
解题思路
用结构体数组来存树。每个节点记录该节点的父亲节点和左右孩子的节点下标,元素值,还有层数。用map来记录各元素值所对应的节点下标。建树,然后根据输入处理即可。
代码如下
#include <iostream>
#include <map>
#include <cctype>
#define maxn 105
using namespace std;
struct node{
int lch, rch;
int fa, step;
int data;
};
node tree[maxn];
void add_node(int x, int k)
{
tree[k].lch = tree[k].rch = 0;
tree[k].data = x;
if(k == 1){
tree[k].fa = 0;
tree[k].step = 1;
return;
}
int now = 1;
int last = 0;
int step = 1;
while(now){
last = now;
if(x < tree[now].data){
now = tree[now].lch;
if(now == 0)
tree[last].lch = k;
}
else{
now = tree[now].rch;
if(now == 0)
tree[last].rch = k;
}
step ++;
}
tree[k].fa = last;
tree[k].step = step;
}
map<int, int> mp;
int main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i ++){
int x;
cin >> x;
add_node(x, i);
mp[x] = i;
}
int m;
cin >> m;
for(int i = 0; i < m; i ++){
int x;
cin >> x;
string str;
int y = 0;
int flg = 0;
while(cin >> str){
if(str == "root"){
if(x == tree[1].data)
cout << "Yes" << endl;
else
cout << "No" << endl;
break;
}
if(isdigit(str[0]) || str[0] == '-'){
int e = 1;
int s = 0;
if(str[0] == '-'){
e = -1;
s = 1;
}
for(int i = s; i < str.size(); i ++)
y = y * 10 + str[i] - '0';
y *= e;
if(flg == 3){
if(mp[x] && mp[y] && tree[mp[y]].fa == mp[x])
cout << "Yes" << endl;
else
cout << "No" << endl;
}
else if(flg == 4){
if(mp[x] && mp[y] && tree[mp[y]].lch == mp[x])
cout << "Yes" << endl;
else
cout << "No" << endl;
}
else if(flg == 5){
if(mp[x] && mp[y] && tree[mp[y]].rch == mp[x])
cout << "Yes" << endl;
else
cout << "No" << endl;
}
if(flg)
break;
}
if(str == "siblings"){
if(mp[x] && mp[y] && tree[mp[x]].fa == tree[mp[y]].fa)
cout << "Yes" << endl;
else
cout << "No" << endl;
break;
}
if(str == "parent")
flg = 3;
else if(str == "left")
flg = 4;
else if(str == "right")
flg = 5;
else if(str == "level"){
if(mp[x] && mp[y] && tree[mp[x]].step == tree[mp[y]].step)
cout << "Yes" << endl;
else
cout << "No" << endl;
break;
}
}
}
return 0;
}