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
25分:
思路:
1. 后序中序转层序,与转前序相似,在转前序的过程中,增加变量index,表示当前结点在二叉树的下标(从1开始)
2. 进行一次输出先序的递归,把结点的index和key值 放入vector,然后进行排序,即可按照层序输出
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
struct node
{
int index;
int v;
};
bool cmp(node a, node b) {
return a.index < b.index;
}
int n;
vector<int> postOrder, inOrder;
vector<node> v;
void LayOrder(int inl, int inr, int postr,int index){
if (inl > inr) return;
int i = inl;
while (inl < inr && postOrder[postr] != inOrder[i]) i++;
node a;
a.index = index;
a.v = postOrder[postr];
v.push_back(a);
LayOrder(inl, i-1, postr-1-inr+i, 2 * index);
LayOrder(i+1, inr, postr-1, 2 * index + 1);
}
int main(){
scanf("%d", &n);
postOrder.resize(n),inOrder.resize(n);
for (int i = 0; i < n; i++) scanf("%d", &postOrder[i]);
for (int i = 0; i < n; i++) scanf("%d", &inOrder[i]);
LayOrder(0,n-1,n-1,0);
sort(v.begin(), v.end(), cmp);
for (int i = 0; i < v.size(); i++) {
if (i != 0) cout << " ";
cout << v[i].v;
}
return 0;
}