二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉搜索树。(摘自百度百科)
给定一系列互不相等的整数,将它们顺次插入一棵初始为空的二叉搜索树,然后对结果树的结构进行描述。你需要能判断给定的描述是否正确。例如将{ 2 4 1 3 0 }插入后,得到一棵二叉搜索树,则陈述句如“2是树的根”、“1和4是兄弟结点”、“3和0在同一层上”(指自顶向下的深度相同)、“2是4的双亲结点”、“3是4的左孩子”都是正确的;而“4是2的左孩子”、“1和3是兄弟结点”都是不正确的。
输入格式:
输入在第一行给出一个正整数N(≤),随后一行给出N个互不相同的整数,数字间以空格分隔,要求将之顺次插入一棵初始为空的二叉搜索树。之后给出一个正整数M(≤),随后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
题解:这题在处理字符串时非常巧妙(没见过世面,嘻嘻),只把有用的信息存起来,没用的形式的读入即可。再者就是判断字符串的设计的信息直接存在节点里,每次通过找数据相对应的节点来判断信息即可,大大缩短了代码量。
#include<iostream>
using namespace std;typedef struct BiNode{int data;BiNode *lchild,*rchild,*par;int le;
}BiNode,*BiTree;void Insert(BiTree &T,int a,BiTree pt,int le)
{if(!T){T=new BiNode;T->data=a;T->lchild=T->rchild=NULL;T->par=pt;T->le=le;}else{if(a<T->data)Insert(T->lchild,a,T,le+1);elseInsert(T->rchild,a,T,le+1);}
}BiTree Search(BiTree T,int a)//找数据在树中对应的节点位置
{if(T){if(T->data==a)return T;else if(a<T->data)return Search(T->lchild,a);elsereturn Search(T->rchild,a);}elsereturn NULL;
}/*
void Pre(BiTree T)
{if(T){cout<<T->data<<endl;Pre(T->lchild);Pre(T->rchild);}
}
*/int main()
{int n,m,num;int x,y;string a;BiTree T=NULL;cin>>n;for(int i=0;i<n;i++){cin>>num;Insert(T,num,NULL,1);}//Pre(T);cin>>m;while(m--){cin>>x;cin>>a;if(a=="is"){cin>>a>>a;if(a=="root"){if(T&&T->data==x)cout<<"Yes"<<endl;elsecout<<"No"<<endl;}else if(a=="parent"){cin>>a>>y;BiTree p=Search(T,y);if(p&&p->par&&p->par->data==x)cout<<"Yes"<<endl;elsecout<<"No"<<endl;}else if(a=="left"){cin>>a>>a>>y;BiTree p=Search(T,y);if(p&&p->lchild&&p->lchild->data==x)cout<<"Yes"<<endl;elsecout<<"No"<<endl;}else if(a=="right"){cin>>a>>a>>y;BiTree p=Search(T,y);if(p&&p->rchild&&p->rchild->data==x)cout<<"Yes"<<endl;elsecout<<"No"<<endl;}}else if(a=="and"){cin>>y;cin>>a;cin>>a;if(a=="siblings"){BiTree p1=Search(T,x);BiTree p2=Search(T,y);if(p1&&p2&&p1->par&&p2->par&&p1->par==p2->par)cout<<"Yes"<<endl;elsecout<<"No"<<endl;}else{cin>>a>>a>>a;BiTree p1=Search(T,x);BiTree p2=Search(T,y);if(p1&&p2&&p1->le==p2->le)cout<<"Yes"<<endl;elsecout<<"No"<<endl;}}}return 0;
}