题目
Suppose that all the keys in a binary tree are distinct positive integers.Given the postorder and inorder traversal sequences, you are supposed to outputthe level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first linegives a positive integer N (<=30), the total number of nodes in the binarytree. The second line gives the postorder sequence and the third line gives theinorder 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 sequenceof the corresponding binary tree. All the numbers in a line must be separatedby 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
步骤,假设有n个数
1、取后续遍历的最后一个数(即根)
2、在中序遍历中找到这个数。
3、中续遍历的根前边的n1个数为左子树,后边的n2个数为右子树,n=n1+n2+1。
4、后续遍历的前n1个为左子树,之后的n2个为右子树。
5、重复。
由此可以构建出相应的树,再bfs即可层续输出
代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct node //二叉树中的点
{
int key;
node* left;
node* right;
};
node* Build_tree(vector<node>::iterator post_begin,vector<node>::iterator post_end,vector<node>::iterator in_begin,vector<node>::iterator in_end);
//根据信息构建二叉树
int main()
{
int n,i;
cin>>n;
node temp,*root;
temp.left=NULL;
temp.right=NULL;
vector<node> postorder,inorder; //两种编列数据,!!!其实用数组比较简单……
for(i=0;i<n;i++) //输入数据
{
cin>>temp.key;
postorder.push_back(temp);
}
for(i=0;i<n;i++)
{
cin>>temp.key;
inorder.push_back(temp);
}
root=Build_tree(postorder.begin(),postorder.end(),inorder.begin(),inorder.end()); //获取树
queue<node> level; //bfs,层次输出
level.push(*root); //压入根节点
do
{
temp=level.front();
level.pop();
if(temp.left!=NULL)
level.push(*temp.left);
if(temp.right!=NULL)
level.push(*temp.right);
if(!level.empty())
cout<<temp.key<<" ";
else
cout<<temp.key;
}while(!level.empty());
return 0;
}
node* Build_tree(vector<node>::iterator post_begin,vector<node>::iterator post_end,vector<node>::iterator in_begin,vector<node>::iterator in_end)
{
vector<node>::iterator i,j;
if(post_end-post_begin==0)
return NULL;
node root=*(post_end-1);
j=post_begin;
for(i=in_begin;i<in_end;i++,j++)
{
if((*i).key==root.key)
break;
}
vector<node>::iterator pl_end,pr_first,il_end,ir_first;
(*(post_end-1)).left=Build_tree(post_begin,j,in_begin,i);
(*(post_end-1)).right=Build_tree(j,post_end-1,i+1,in_end);
return &(*(post_end-1));
}