题目链接
题目描述
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
结尾无空行
题目大意
给出一棵树的中序和后序遍历结果,求这棵树的层序遍历
解题思路
就相当于中序和后序遍历转换为先序遍历,其中每一个递归中的根节点就是需要找的节点
注意因为可能树的高度很高,所以最好不要用数组存层序遍历的数据,最好用map来存储
具体算法可以参考之前的文章
【算法】【树】已知后序中序序列求先序序列_Elephant_King的博客-CSDN博客
题解
#include<bits/stdc++.h>
using namespace std;
int n;
vector<int> in,post;
map<long long,int> ma;
void preOrder(int root,int start,int end,int index){
if(start>end) return ;
int i=start;
while(i<end&&in[i]!=post[root]) i++;
ma[index]=post[root];
preOrder(root-(end-i+1),start,i-1,index*2+1);
preOrder(root-1,i+1,end,index*2+2);
}
int main(){
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];
}
preOrder(n-1,0,n-1,0);
for(auto it=ma.begin();it!=ma.end();it++){
if(it!=ma.begin()) cout<<" ";
cout<<it->second;
}
}