2019年pat春季第四题
本题考察知识点有,树的重建,字符串处理,查找结点对应指正,查找树中结点的父节点,判断树的结点的深度,判断树是否为满树(除叶结点外都有左右子树)。
#include<bits/stdc++.h>
using namespace std;
int n,m;
int post[35],in[35];
bool flag=true;
struct Node{
int data,level,father;
Node* lchild;
Node* rchild;
};
void create(int postl,int postr,int inl,int inr,Node* &root){
if(postl>postr)return;
int i;
for(i=inl;i<=inr;i++){
if(in[i]==post[postr])
break;
}
root=new Node;
root->lchild=root->rchild=NULL;
root->data=in[i];
create(postl,postl+i-1-inl,inl,i-1,root->lchild);
create(postr-inr+i,postr-1,i+1,inr,root->rchild);
}
void DFS(Node* &root,int level){
if(root==NULL)return;
root->level=level;
DFS(root->lchild,level+1);
DFS(root->rchild,level+1);
}
void DFS1(Node* root){
if(root->lchild!=NULL){root->lchild->father=root->data;
DFS1(root->lchild);}
if(root->rchild!=NULL){root->rchild->father=root->data;
DFS1(root->rchild);}
return;
}
void full(Node* root){
if(root->lchild==NULL&&root->rchild==NULL)return;
else if(root->lchild!=NULL&&root->rchild==NULL){flag=false;
return;}
else if(root->rchild!=NULL&&root->lchild==NULL){flag=false;
return;}
else {full(root->lchild);
full(root->rchild);}
}
Node* find(Node* &root,int v){
queue<Node*>Q;
Q.push(root);
while(!Q.empty()){
Node* now=Q.front();
Q.pop();
if(now->data==v)return now;
if(now->lchild!=NULL)Q.push(now->lchild);
if(now->rchild!=NULL)Q.push(now->rchild);
}
return NULL;
}
int main(){
cin>>n;
string s,u,p;
for(int i=0;i<n;i++)
scanf("%d",&post[i]);
for(int i=0;i<n;i++)
scanf("%d",&in[i]);
Node* root=NULL;
create(0,n-1,0,n-1,root);
DFS(root,0);
DFS1(root);
cin>>m;
getchar();
while(m--){
getline(cin,s);
int v1,v2;
Node* r1=NULL;
Node* r2=NULL;
if(s.find("full")!=-1)
{ full(root);
printf("%s\n",flag?"Yes":"No");
continue;}
if(s.find("root")!=-1)
{ sscanf(s.c_str(),"%d is the root",&v1);
printf("%s\n",v1==root->data?"Yes":"No");
continue;
}
if(s.find("siblings")!=-1){
sscanf(s.c_str(),"%d and %d are siblings",&v1,&v2);
r1=find(root,v1);
r2=find(root,v2);
printf("%s\n",r1->father==r2->father?"Yes":"No");
continue;
}
if(s.find("parent")!=-1){
sscanf(s.c_str(),"%d is the parent of %d",&v1,&v2);
r2=find(root,v2);
printf("%s\n",r2->father==v1?"Yes":"No");
continue;
}
if(s.find("left")!=-1){
sscanf(s.c_str(),"%d is the left child of %d",&v1,&v2);
r2=find(root,v2);
if(r2->lchild==NULL){printf("No\n");
continue;}
else
{ printf("%s\n",r2->lchild->data==v1?"Yes":"No");
continue;}
}
if(s.find("right")!=-1){
sscanf(s.c_str(),"%d is the right child of %d",&v1,&v2);
r2=find(root,v2);
if(r2->rchild==NULL){printf("No\n");
continue;}
else
{ printf("%s\n",r2->rchild->data==v1?"Yes":"No");
continue;}
}
if(s.find("level")!=-1){
sscanf(s.c_str(),"%d and %d are on the same level",&v1,&v2);
r1=find(root,v1);
r2=find(root,v2);
printf("%s\n",r1->level==r2->level?"Yes":"No");
continue;
}
}
return 0;
}