1020 Tree Traversals (25 分)
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 7
Sample Output:
4 1 6 3 5 7 2
题意简单清楚,注意建树时的序列划分
参考代码:
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=50;
struct node {
int data;
node* lchild;
node* rchild;
};
int pre[maxn],in [maxn], post[maxn];
int n;
//当前二叉树的后序序列区间为[postL,postR],中序序列为[inL,inR];
//create 函数返回构建出的二叉树的根节点的地址
node * create(int postL,int postR,int inL,int inR)
{
if(postL>postR)
return NULL; //后序序列长度小于等于0时,直接返回
node* root =new node;//创建根节点
root ->data=post[postR];
int k;
for(k=inL;k<=inR;++k)
{
if(in[k]==post[postR])//在中序序列中找到in[k]==pre[l]的结点
break;
}
int numleft=k-inL;//左子树节点个数
//递归建立左子树,返回左子树的根节点地址,赋值为root所指左指针
root->lchild=create(postL,postL+numleft-1,inL,k-1);
//递归建立右子树返回右子树的根节点地址,赋值为root所指右指针
root->rchild=create(postL+numleft,postR-1,k+1,inR);
return root;
}
int num=0;//已输出的结点个数
void BFS(node* root)
{
queue<node*> q;//注意队列中存地址
q.push(root);
while(!q.empty())
{
node* p=q.front();
q.pop();
printf("%d",p->data);
num++;
if(num<n)
printf(" ");//访问队首元素
if(p->lchild)
q.push(p->lchild); //左子树非空
if(p->rchild)
q.push(p->rchild);
}
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;++i)
{
scanf("%d",&post[i]);
}
for(int i=0;i<n;++i)
{
scanf("%d",&in[i]);
}
node*root=create(0,n-1,0,n-1);//建树
BFS(root);//层序遍历
return 0;
}