版权声明:有疑问请在评论区回复,邮箱:[email protected] https://blog.csdn.net/qq_40946921/article/details/87942284
L3-016 二叉搜索树的结构 (30 分)
二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉搜索树。(摘自百度百科)
给定一系列互不相等的整数,将它们顺次插入一棵初始为空的二叉搜索树,然后对结果树的结构进行描述。你需要能判断给定的描述是否正确。例如将{ 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
注意: 有可能查询的数结点,并不存在(例如题目样例,查询结点8)(测试点2)
完整测试数据分析:来源(https://blog.csdn.net/Dream_Weave/article/details/82744830)
#include<iostream>
#include<string>
#include<map>
using namespace std;
struct Node {
int height;
int parent = -1;
int left=-1, right=-1;
};
map<int, Node> tree;
void insert(int head, int tmp,int height) { //构造搜索树
if (head != -1) {
int r = tmp < head ? tree[head].left : tree[head].right;
if (r != -1)
insert(r, tmp,height+1);
else {
(tmp < head ? tree[head].left : tree[head].right) = tmp;
tree[tmp].parent = head; //记录父结点
tree[tmp].height = height; //存储结点深度
}
}
}
bool judge(int head,int a, int b, string link) {
if (link == "root")
return head == a;
if (tree.find(a) == tree.end() || tree.find(b) == tree.end()) //当搜索的结点不在树中,返回false
return false;
else if (link == "siblings")
return tree[a].parent==tree[b].parent;
else if (link == "parent")
return tree[a].left == b || tree[a].right == b;
else if (link == "left")
return tree[b].left == a;
else if (link == "right")
return tree[b].right == a;
else if (link == "level")
return tree[a].height == tree[b].height;
}
int main() {
int n, m, tmp, a=0, b=0, head;
string link, str;
cin >> n >> head;
for (int i = 1; i < n; i++) {
cin >> tmp;
insert(head, tmp, 1);
}
cin >> m;
for (int i = 0; i < m; i++) {
cin >> a >> str;
if (str == "and") {
cin >> b >> str >> str;
if (str == "siblings")
link = str;
else
cin >> str >> str >> link;
}
else {
cin >> str >> link;
if (link == "parent")
cin >> str >> b;
else if(link!="root")
cin >> str >> str >> b;
}
cout << (judge(head, a, b, link) ? "Yes" : "No") << endl;
}
return 0;
}