您的位置:首页 > 其它

1020. Tree Traversals (25)

2015-01-30 22:03 204 查看
题目:

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


注意:
1、这个是重构二叉树的问题,在《编程之美》的3.9节有较为详细的解答,其中是已知前序和中序来重构二叉树,这里是已知后序和中序来重构,思路是类似的。
2、要求以层序输出,其实也就是用广度优先遍历BFS的方法,我这里是用的vector来做的,标准的BFS应该用queue来做,但是思路是一致的。

代码:

#include<iostream>
#include<vector>
using namespace std;
struct node
{
int val;
node *left;
node *right;
}root;
int postorder[32];
int inorder[32];

void rebuild(int sp,int ep, int si,int ei,node *subroot)
//sp :start index of postorder sequence
//ep :end index of postorder sequence
//si :start index of inorder sequence
//ei :end index of inorder sequence
{
(*subroot).val=postorder[ep];
(*subroot).left=NULL;
(*subroot).right=NULL;
//if only one node in the tree
if(sp==ep)
return;
int i=si;
//find the root of the tree in the inorder sequence
while(postorder[ep]!=inorder[i])
++i;
//if left subtree exists
if(i>si)
{
node *left= new node;
(*subroot).left=left;
rebuild(sp,sp+i-si-1,si,i-1,left);
}
//if right subtree exists
if(i<ei)
{
node *right= new node;
(*subroot).right=right;
rebuild(sp+i-si,ep-1,i+1,ei,right);
}
}
void levelorder(node *root)
{
cout<<(*root).val;
//child is the vector of nodes in the current level
//temp is the vector of nodes in the next level
vector<node*> child,temp;
if((*root).left!=NULL)
child.push_back((*root).left);
if((*root).right!=NULL)
child.push_back((*root).right);
while(!child.empty())
{
int l=child.size();
temp.clear();
for(int i=0;i<l;++i)
{
//for each node in the current level
//add their child node into the next level
node *n=child.at(i);
cout<< ' '<<(*n).val;
if((*n).left != NULL)
temp.push_back((*n).left);
if((*n).right != NULL)
temp.push_back((*n).right);
}
child=temp;
}
}
int main()
{
int N;//the total number of nodes in the binary tree
cin>>N;
int i;
for(i=0;i<N;++i)
cin>>postorder[i];
for(i=0;i<N;++i)
cin>>inorder[i];
rebuild(0,N-1,0,N-1,&root);
levelorder(&root);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: