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
分析
本题考查的是树的遍历,此处扩展了博客[^1]的解法,将博客的例子中序列的起点和终点分开透彻地阐述了,但是题主在做本题时仍然还是花了一些时间做调试工作,说明对此类题目理解得还不够透彻,因此仍继续追加记录以做理解。
注意点1:本题在计算左右子树起点和终点的时,器依靠子树的长度做相对i的偏移进行计算的,不能简单的认为中序和后序处于对齐状态,这个思考是错误的,但是往往做题出现迷糊的时容易产生两序列对齐的错觉,从而没有依据长度偏移计算点的索引。透彻地说,我们计算的时候有五个锚点,函数提供的左右子树的起点终点四个锚点和中序中找出的根节点一个锚点,然后计算新的左右子树的起点和终点是依据五个锚点和子树长度(做偏移)求解的。
注意点2:递归终止的条件是当起点跑到终点的后面,这是不合理的,以此作为递归终止点;另外在中序中找寻根节点时,i的搜索范围是i<inright,不能涵盖等号,这个还未找到合理的解释,后续再做领悟。
#include <iostream>
#include <vector>
using namespace std;
vector<int> post,in;
vector<int> a[30];
FILE *f;
void getpre(int postleft,int postright,int inleft,int inright,int height){
if(postleft>postright || inleft>inright) return ;
int i=inleft;
while(i<inright && post[postright]!=in[i]) i++;
// cout<<post[postright];
a[height].push_back(post[postright]);
getpre(postleft,postleft+i-inleft-1,inleft,i-1,height+1);
getpre(postleft+i-inleft,postright-1,i+1,inright,height+1);
}
int main(){
int n;
cin>>n;
in.resize(n),post.resize(n);
for(int i=0;i<n;i++) cin>>post[i];
for(int i=0;i<n;i++) cin>>in[i];
getpre(0,n-1,0,n-1,0);
bool first=true;
for(int i=0;i<30;i++){
for(int j=0;j<a[i].size();j++){
if(first){
cout<<a[i][j];
first=false;
}else cout<<" "<<a[i][j];
}
}
return 0;
}