7-10 树的遍历 (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
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
int a[1000],b[1000];
struct node
{
int data;
struct node *l,*r;
}*p;
int k=0;
int n;
struct node *digui(int *a,int *b,int len)
{
if(len==0)return NULL;
struct node *p;
p=(struct node*)malloc(sizeof(struct node));
p->data=b[len-1];
int i;
for(i=0; i<len; i++)
{
if(b[len-1]==a[i])break;
}
p->l=digui(a,b,i);
p->r=digui(a+i+1,b+i,len-i-1);
return p;
}
void cengxu(struct node *root)
{ //存下树的每一个节点
struct node *q[1000];
int out=0,in=0;
q[in++]=root; //存下第一个
while(in>out) //遍历出口,当in=out时,说明没有节点了
{
if(q[out]) //如果这个节点存在,说明它可能有子节点,所以if
{
k++;
if(k<n)printf("%d ",q[out]->data); //按层次输出
else printf("%d",q[out]->data);
q[in++]=q[out]->l; // 先左后右,in可以当作是树的节点数
q[in++]=q[out]->r; //当in=n时,说明跑完了所有
}
out++;
}
}
int main()
{
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%d",&b[i]);
}
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
p=digui(a,b,n);
cengxu(p);
printf("\n");
return 0;
}