本来想着把树的存储结构都用一遍,但是后来在想如何处理输出的时候想到可以直接利用二叉树的顺序存储判断statement,感觉比二叉链表容易一些
对输入处理的方法参考了:
https://blog.csdn.net/a845717607/article/details/88083836/
AC代码
#include<bits/stdc++.h>
using namespace std;
#define INF 100000000
map<int,int > ValueToIndex;
int postorder[35];
int inorder [35];
map <int,int>levelorder;
int leafCount=0;
void PostAndInToLevel(int root,int start,int end,int index)
{
if(start>end) {return;}
int i=start;
while(i<end&&inorder[i]!=postorder[root]) i++;
levelorder[index]=postorder[root];
ValueToIndex[postorder[root]]=index;
if((start>i-1)&&(end<i+1)) leafCount++;//to count leaves
PostAndInToLevel(root-(end-i)-1,start,i-1,index*2);
PostAndInToLevel(root-1,i+1,end,index*2+1);
}
int main()
{
int N;
cin>>N;
for(int i=0;i<N;i++)
{
int t;
cin>>t;
postorder[i]=t;
}
for(int i=0;i<N;i++)
{
int t;
cin>>t;
inorder[i]=t;
}
PostAndInToLevel(N-1,0,N-1,1);
int M;
cin>>M;
getchar();//getchar() to process '\n'
/*
for(auto it=ValueToIndex.begin();it!=ValueToIndex.end();it++)
{
cout<<it->second<<" "<<it->first<<"\n";
}
*/
// process statement
for(int i=0;i<M;i++)
{
string s;
getline(cin,s);
if(s.find("full")!=string::npos)//use find() to know which type statement it is
{
if(N-leafCount==leafCount-1)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
else if(s.find("root")!=string::npos)
{
int r;
sscanf(s.c_str(),"%d is the root",&r);
if(ValueToIndex[r]==1)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
else if(s.find("level")!=string::npos)
{
int a,b;
sscanf(s.c_str(),"%d and %d are on the same level",&a,&b);//use sscanf!!!
int l1=log2(ValueToIndex[a]);
int l2=log2(ValueToIndex[b]);
if(l1==l2)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
else if (s.find("siblings")!=string::npos)
{
int a,b;
sscanf(s.c_str(),"%d and %d are siblings",&a,&b);
if(ValueToIndex[b]/2==ValueToIndex[a]/2)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
else if (s.find("left")!=string::npos)
{
int a,b;
sscanf(s.c_str(),"%d is the left child of %d",&a,&b);
if(ValueToIndex[b]*2==ValueToIndex[a])
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
else if (s.find("right")!=string::npos)
{
int a,b;
sscanf(s.c_str(),"%d is the right child of %d",&a,&b);
if(ValueToIndex[b]*2+1==ValueToIndex[a])
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
else if(s.find("parent")!=string::npos)
{
int a,b;
sscanf(s.c_str(),"%d is the parent of %d",&a,&b);
if(ValueToIndex[b]/2==ValueToIndex[a])
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return 0;
}