7-4 树的遍历
分数 20
作者 陈越
单位 浙江大学
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
C++ (g++)
思路:
① 创建树
② 层序遍历树
①
如果结点数<0,返回空。
给树申请内存空间,记录根结点的值,寻找根结点在中序遍历中的位置,递归创建左子树,递归创建右子树,返回创建的树T
②
将树入队,长度置为0。
输出队头元素,注意格式,结尾不能有多余空格。
左子树入队,右子树入队。队头元素(根结点)出队。
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef struct Tree
{
int data;
struct Tree *left,*right;
}*BT;
queue<BT> p;
BT creat(int *post,int *in, int n)
{
int i;
if(n<=0) return NULL;
BT T=(BT)malloc(sizeof(struct Tree));
T->data=post[n-1];
for(i=0;i<n;i++)
{
if(in[i]==post[n-1])
break;
}
T->left=creat(post,in,i);
T->right=creat(post+i,in+i+1,n-i-1);
return T;
}
void LeverOrder(BT T,int n)
{
if(T==NULL) return;
p.push(T);
int length=0;
while(!p.empty())
{
BT t=p.front();
length++;
if(length<n)
cout<<t->data<<" ";
else
cout<<t->data;
if(t->left) p.push(t->left);
if(t->right) p.push(t->right);
p.pop();
}
}
int main()
{
int N;
cin>>N;
int post[N],in[N];
for(int i=0;i<N;i++)
{
cin>>post[i];
}
for(int i=0;i<N;i++)
{
cin>>in[i];
}
BT T=creat(post,in,N);
LeverOrder(T,N);
return 0;
}