题目如下:
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:7 2 3 1 5 7 6 4 1 2 3 4 5 6 7Sample Output:
4 1 6 3 5 7 2
题目要求很简单,给一个二叉树的后序遍历和中序遍历,给出该二叉树的层次遍历的序列。基本上给张图都能够几下画出来。我一开始尝试了一下不构建二叉树直接从后序和中序遍历的序列得到结果,不过可能我太挫了,想用递归解决不过老是弄成深搜了,层次没出来。所以最后还是用了个笨方法,就是先根据序列构建二叉树,然后用队列将其层次化序列打印出来。
二叉树的构建不难,用递归可以解决,后序序列的最后一个值是二叉树的根节点,然后在中序序列中,根节点左边的是其左孩子,右边的是其右孩子。然后分别在其左右孩子序列调用递归找到根节点作为该节点的左右孩子结点。
二叉树构建完成了,其层次遍历就很简单了,用一个队列就可以搞定。
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct binary_tree
{
int value;
struct binary_tree *left;
struct binary_tree *right;
}bt;
int post_order[32],in_order[32],level_order[32];
int n;
void init(bt *t);
int find_ptr(int *order,int num);
bt* find_root(int left,int right);
int main(int argc,char* argv[])
{
int i,rt_ptr,front,rear;
bt root;
bt* queue[40];
//freopen("input","r",stdin);
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&post_order[i]);
for(i=0;i<n;i++)
scanf("%d",&in_order[i]);
init(&root);
root.value = post_order[n-1];
rt_ptr = find_ptr(in_order,root.value);
root.left = find_root(0,rt_ptr-1);
root.right = find_root(rt_ptr+1,n-1);
//put the binary tree into queue
front = rear = 0;
queue[rear++] = &root;
while(front != rear)
{
if(front != n-1)
printf("%d ",queue[front]->value);
else
printf("%d\n",queue[front]->value);
if(queue[front]->left != NULL)
queue[rear++] = queue[front]->left;
if(queue[front]->right != NULL)
queue[rear++] = queue[front]->right;
front++;
}
return 0;
}
void init(bt *b)
{
b->left = NULL;
b->right = NULL;
}
int find_ptr(int *order,int num)
{
int i;
for(i=0;i<n;i++)
if(order[i] == num)
return i;
return -1;
}
bt* find_root(int left,int right)
{
//printf("left: %d right: %d\n",left,right);
int i,ptr,max,max_i;
bt *btree;
btree = (bt*)malloc(sizeof(bt));
init(btree);
if(left > right)
return NULL;
if(left == right)
{
btree->value = in_order[left];
return btree;
}
max = -1;
for(i=left;i<=right;i++)
{
ptr = find_ptr(post_order,in_order[i]);
if(ptr > max)
{
max = ptr;
max_i = i;
}
}
btree->value = post_order[max];
btree->left = find_root(left,max_i-1);
btree->right = find_root(max_i+1,right);
return btree;
}