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
题目的意思是已知二叉树的后序遍历序列和中序遍历序列的前提下,输出该二叉树按层遍历的序列。
思路:
由于后序遍历的顺序是LRN,所以后序遍历序列的最后一个元素是当前二叉树的根。在中序遍历中确定该元素的位置,则可以确定剩余元素属于左子树还是右子树。递归地对左右子树进行操作。
本来理想的实现是能够控制所有的递归同步进行,这样就可以在上述处理过程中直接输出层序遍历的结果了。不过因为递归是一直到终止项才会结束,所以通过编程实现上述步骤得到的是该二叉树的先序遍历的结果。因此 ,在上述处理中将当前处理到的元素保存到一个记录每一层元素的数组中,数组的每一项是一个vector,保存当前层从左向右的元素。这样在操作完成后就可以得到层序序列了。
实现代码:
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
vector<int> res[31]; //存放层遍历结果
int max_depth=0;
void recur(vector<int> in_order,vector<int> post_order,int depth){
int len = in_order.size();
if(len == 0)
return;
else if(len == 1){
// cout << in_order[0] << " ";
res[depth].push_back(in_order[0]);
max_depth = max_depth < depth ? depth : max_depth;
return;
}
//选择后序遍历序列最后一个,并且在中序序列中找到该元素
//将该元素输出,之后递归处理左右半边
int last_ele = post_order[len-1];
int ind=0;
for(;ind<len;++ind)
if(in_order[ind] == last_ele)
break;
// cout << last_ele << " ";
res[depth].push_back(last_ele);
if(ind != 0){
vector<int> in_left(in_order.begin(),in_order.begin()+ind);
vector<int> post_left(post_order.begin(),post_order.begin()+ind);
recur(in_left,post_left,depth + 1);
}
if(ind+1 != len){
vector<int> in_right(in_order.begin()+ind+1,in_order.end());
vector<int> post_right(post_order.begin()+ind,post_order.begin()+len-1);
recur(in_right,post_right,depth + 1);
}
}
int main(int argc, char const *argv[])
{
vector<int> in_order,post_order;
int n_cnt;
scanf(" %d",&n_cnt);
if(n_cnt == 0)
return 0;
for(int i=0;i<n_cnt;++i){
post_order.push_back(0);
cin >> post_order[i];
}
for(int j=0;j<n_cnt;++j){
in_order.push_back(0);
cin >> in_order[j];
}
if(n_cnt == 1){
cout << in_order[0];
return 0;
}
recur(in_order,post_order,0);
vector<int>::iterator iter;
for(int i=0;i<=max_depth;++i){
iter = res[i].begin();
while(iter != res[i].end()){
if(i == max_depth && iter + 1 == res[i].end())
cout << *iter;
else
cout << *iter << " ";
++iter;
}
}
return 0;
}