7-6 树的遍历(25 分)
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
/*
7-6 树的遍历
*/
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int hou[1000],zhong[1000];
struct node{
int data;
struct node *left,*right;
}T;
struct node *creat(int hou[],int zhong[],int n){
int i,k,root;
if(n==0)
return NULL;
struct node *T;
T=(struct node *)malloc(sizeof(struct node));
root=hou[n-1];
T->data=root;
for(i=0;i<n;i++){
if(zhong[i]==root){
k=i;
break;
}
}
T->left=creat(hou,zhong,k);
T->right=creat(hou+k,zhong+k+1,n-k-1);
return T;
}
void cengci(struct node *T,int n){
struct node* p[1000],*q;
int f=0,r=0;
int num=0;
if(T){
p[r++]=T;
while(f!=r){
q=p[f++];
printf("%d",q->data);
num++;
if(num<n)
cout<<" ";
if(q->left){
p[r++]=q->left;
}
if(q->right){
p[r++]=q->right;
}
}
}
}
int main(){
int n,i;
struct node *T;
cin>>n;
for(i=0;i<n;i++)
cin>>hou[i];
for(i=0;i<n;i++)
cin>>zhong[i];
T=creat(hou,zhong,n);
cengci(T,n);
return 0;
}