Step 1 Problem:
给n个结点的搜索树,m个询问,满足输出”Yes”,否则”No”。
询问格式有六种:
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在同一层上”。
数据范围:
正整数:n<=100, m<=100
Step 2 Involving algorithms:
搜索树
Step 3 Ideas:
多加一个指针,指向父亲,询问就很容易解决了。
注意:如果结点是空的时候,不能访问它的数据。
Step 4 Code:
#include<bits/stdc++.h>
using namespace std;
struct node
{
int num;
node *lt, *rt, *fq;//指向左孩子,右孩子,父亲
};
node *tmp;
int hg(node *root)//求高度
{
int h = 0;
while(root->fq)
{
h++;
root = root->fq;
}
return h;
}
node *Insert(node *root, int num)//建树
{
if(root == NULL)
{
root = new node;
root->num = num;
root->lt = root->rt = NULL;
} else
{
if(num < root->num)
{
root->lt = Insert(root->lt, num);
if(root->lt)
root->lt->fq = root;
}
else
{
root->rt = Insert(root->rt, num);
if(root->rt)
root->rt->fq = root;
}
}
return root;
}
void Find(node *root, int num)//查询结点是否存在
{
if(root && !tmp)
{
if(root->num == num) {
tmp = root;
return;
}
Find(root->lt, num);
Find(root->rt, num);
}
}
char s[100];
int main()
{
int n, num, q;
cin >> n;
node *head = NULL;
for(int i = 0; i < n; i++)
{
scanf("%d", &num);
head = Insert(head, num);
}
head->fq = NULL;
//printf("%d\n", head->d);
scanf("%d", &q);
getchar();
char ok[100];
int A, B;
while(q--)
{
tmp = NULL;
gets(s);
sscanf(s, "%*s %*s %*s %s", ok);
if(strcmp(ok, "root") == 0)
{
sscanf(s, "%d", &A);
Find(head, A);
if(tmp == NULL || tmp->num != head->num) printf("No\n");
else printf("Yes\n");
}
else if(strcmp(ok, "parent") == 0)
{
sscanf(s, "%d %*s %*s %*s %*s %d", &A, &B);
Find(head, B);
if(tmp == NULL) printf("No\n");
else
{
if(tmp->fq && tmp->fq->num == A) printf("Yes\n");
else printf("No\n");
}
}
else if(strcmp(ok, "left") == 0)
{
sscanf(s, "%d %*s %*s %*s %*s %*s %d", &A, &B);
Find(head, B);
if(tmp == NULL) printf("No\n");
else
{
if(tmp->lt && tmp->lt->num == A) printf("Yes\n");
else printf("No\n");
}
}
else if(strcmp(ok, "right") == 0)
{
sscanf(s, "%d %*s %*s %*s %*s %*s %d", &A, &B);
Find(head, B);
if(tmp == NULL) printf("No\n");
else
{
if(tmp->rt && tmp->rt->num == A) printf("Yes\n");
else printf("No\n");
}
}
else
{
sscanf(s, "%d %*s %d %*s %s", &A, &B, ok);
if(strcmp(ok, "siblings") == 0)
{
Find(head, A);
if(tmp == NULL) printf("No\n");
else
{
node *tt = tmp->fq;
tmp = NULL;
Find(head, B);
if(tmp == NULL) printf("No\n");
else
{
if(tmp->fq == tt) printf("Yes\n");
else printf("No\n");
}
}
}
else
{
Find(head, A);
if(tmp == NULL) printf("No\n");
else
{
int t = hg(tmp);
tmp = NULL;
Find(head, B);
if(tmp == NULL) printf("No\n");
else
{
if(hg(tmp) == t) printf("Yes\n");
else printf("No\n");
}
}
}
}
}
return 0;
}