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
解题思路:
题目中给出一颗树的后序和中序结果,我们只要根据这个写出树的先序,然后加上下标输出就可以得到树的层序结果就是下面这个代码:
void pre(int root,int start,int end,int index){
if(start>end) return;
int i=start;
while(i<end&&in[i]!=post[root]) i++;
result.push_back({index,post[root]});
pre(root-1-end+i,start,i-1,2*index+1);
pre(root-1,i+1,end,2*index+2);
}
其实和你根据后序和中序重新建立一颗二叉树再输出的想法是有点类似的。其中root就是当前的根在后序输出中的下标,start和end都是根据中序输出的下标来决定的。因为后序输出的顺序是左右根,中序输出的顺序是左根右,所以可以根据后序来确定根的位置,再在中序中找到这个根,来划分左右树。
index就是输出节点在树中按层序输出的下标。因为先序输出的顺序是根左右。所以左子树的下标应该是2*index+1,右子树就是2*index+2,因为在递归里左右子树其实是先后进行的,所以要乘以2把另一半子树的下标也考虑进去。
代码:
#include<bits/stdc++.h>
using namespace std;
int N;
int post[1000];
int in[1000];
typedef struct tree{
int index;
int value;
};
vector<tree> result;
void read(int a[]){
for(int i=0;i<N;i++)
cin>>a[i];
}
bool cmp(tree a,tree b){
return a.index<b.index;
}
void pre(int root,int start,int end,int index){
if(start>end) return;
int i=start;
while(i<end&&in[i]!=post[root]) i++;
result.push_back({index,post[root]});
pre(root-1-end+i,start,i-1,2*index+1);
pre(root-1,i+1,end,2*index+2);
}
int main(){
cin>>N;
read(post);read(in);
pre(N-1,0,N-1,0);
sort(result.begin(),result.end(),cmp);
for(auto i=result.begin();i!=result.end();i++){
tree a=*i;
cout<<a.value;
if(i!=result.end()-1) cout<<" ";
}
return 0;
}
如果想看建树来解决这个问题的算法可以看算法笔记https://blog.csdn.net/qq_34767784/article/details/104309673