给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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 <stdlib.h>
typedef int ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
int post[30],in[30];
BinTree Build(int head1,int tail1,int head2,int tail2);
void LevelorderTraversal( BinTree BT );
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&post[i]);
}
for(i=0;i<n;i++){
scanf("%d",&in[i]);
}
BinTree BT=Build(0,n-1,0,n-1);
LevelorderTraversal(BT);
return 0;
}
BinTree Build(int head1,int tail1,int head2,int tail2){
int num=post[tail1];//找到根结点
int i;
for(i=head2;i<=tail2;i++){//在中序找到根结点
if(num==in[i]){
break;
}
}
BinTree T=(BinTree)malloc(sizeof(struct TNode)) ;
T->Data=num;
int left,right;
left=i-head2;right=tail2-i;//左右子树结点个数
if(left==0) T->Left=NULL;
else
T->Left=Build(head1,head1+left-1,head2,head2+left-1);
if(right==0) T->Right=NULL;
else
T->Right=Build(i,tail1-1,i+1,tail2);
return T;
}
void LevelorderTraversal( BinTree BT ){
if(!BT) return ;
BinTree T[100];
BinTree t;
int rear=0,front=0;
T[rear++]=BT;
int flag=0;
while(rear!=front){
t=T[front++];
if(flag){
printf(" ");
}
printf("%d",t->Data);
flag=1;
if(t->Left) T[rear++]=t->Left;
if(t->Right) T[rear++]=t->Right;
}
}
测试点 | 提示 | 结果 | 分数 | 耗时 | 内存 |
---|---|---|---|---|---|
0 | sample等价 | 答案正确 | 15 | 2 ms | 324 KB |
1 | 单个结点 | 答案正确 | 1 | 2 ms | 196 KB |
2 | 左偏 | 答案正确 | 2 | 2 ms | 368 KB |
3 | 右偏 | 答案正确 | 2 | 2 ms | 324 KB |
4 | 左右单边交错 | 答案正确 | 2 | 2 ms | 196 KB |
5 | 最大规模 | 段错误 | 0 | 12 ms | 11724 KB |
这个也不知道是哪里段错误了