题目:
思路分析:
我们可以根据中序遍历和后序遍历的特点找到那个共同的根 中序在中间位置 后序在最后
那么我们就直接在中序中找那个元素就行 然后把分成俩部分就行建树
按层次输出用queue就行 bfs遍历
代码实现:
const int MAX=110;
struct node{
node *l,*r;
int data;
};
int mid[MAX],last[MAX];
int n;
node *creat(int l1,int r1,int l2,int r2){
if(l1>r1||l2>r2){
return NULL;
}
node *root=new node;
root->data=last[r2];
root->l=NULL;
root->r=NULL;
int i;
for(i=l1;i<=r1;i++){
if(mid[i]==last[r2]){
break;
}
}
int num=i-l1;
root->l=creat(l1,i-1,l2,l2+num-1);
root->r=creat(i+1,r1,l2+num,r2-1);
return root;
}
void print(node *root){
queue<node*>qu;
if(root){
qu.push(root);
cout<<qu.front()->data;
}
while (!qu.empty()) {
node *root=qu.front();
qu.pop();
if(root->l){
cout<<" "<<root->l->data;
qu.push(root->l);
}
if(root->r){
cout<<" "<<root->r->data;
qu.push(root->r);
}
}
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>last[i];
}
for(int i=0;i<n;i++){
cin>>mid[i];
}
node *root=NULL;
root=creat(0,n-1,0,n-1);
print(root);
return 0;
}