Description
一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是完美二叉树。对于深度为 D 的,有 N 个结点的二叉树,若其结点对应于相同深度完美二叉树的层序遍历的前 N 个结点,这样的树就是完全二叉树。
给定一棵完全二叉树的后序遍历,请你给出这棵树的层序遍历结果。
Input
输入在第一行中给出正整数 N(≤30),即树中结点个数。第二行给出后序遍历序列,为 N 个不超过 100 的正整数。同一行中所有数字都以空格分隔。
Output
在一行中输出该树的层序遍历序列。所有数字都以 1 个空格分隔,行首尾不得有多余空格。
Sample Input
8
91 71 2 34 10 15 55 18
Sample Output
18 34 55 71 2 10 15 91
参考程序(C语言实现)
#include <stdio.h>
#include <string.h>
#define LEN 100
struct TreeNode
{
int Element;
int LeftChildIndex;
int RightChildIndex;
}FullBinaryTree[LEN+5];
void PostOrderVisit(int index)
{
if(index!=-1)
{
PostOrderVisit(FullBinaryTree[index].LeftChildIndex);
PostOrderVisit(FullBinaryTree[index].RightChildIndex);
scanf("%d",&FullBinaryTree[index].Element);
}
}
int main()
{
int i,N;
scanf("%d",&N);
for(i=1;i<=N;i++)
{
if(i*2<=N)
{
FullBinaryTree[i].LeftChildIndex=2*i;
}
else
{
FullBinaryTree[i].LeftChildIndex=-1;
}
if(2*i+1<=N)
{
FullBinaryTree[i].RightChildIndex=2*i+1;
}
else
{
FullBinaryTree[i].RightChildIndex=-1;
}
}
PostOrderVisit(1);
for(i=1;i<=N-1;i++)
{
printf("%d ",FullBinaryTree[i].Element);
}
printf("%d\n",FullBinaryTree[i].Element);
return 0;
}
分析:首先根据结点数N,是一定可以确定树的结构的,所以先建立一棵没有填数字的“空白的完全二叉树”:对于完全二叉树来说,所使用的的存储结构自然是一维数组,尽管这样看来所有结点都平放在了一行,但是还是可以为结点人为地添加上链接关系:即下标为i的结点,左子结点的下标为2×i,右子结点的下标为2×i+1,因此,构建结构体TreeNode,依次存储本身数值Element,左子结点的索引LeftChildIndex,右子结点的索引RightChildIndex,这样就类似于用二叉链表构建的一棵树,实际上是将各个TreeNode整合在了一个一维的结构体数组里。然后对这个没有填数字的空白树进行后序遍历,边遍历边填数即可。最后再遍历一遍结构体数组,就相当于层次遍历了。