1020. Tree Traversals 后序中序转层序

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

/**
cmp (a,b)  a<b为升序排列 a>b为降序排列

本题思路: 将 后序 中序 转换为层序遍历
1.利用后序 中序遍历 -> 先序遍历性质
2. 利用了完全二叉树下标的性质 左i=2*i+1   右i=2*i+2;

建立一个结构体 存放结点值,与下标索引
进行 利用后序 中序遍历 -> 先序遍历时 , 记录每个结点的下标,(开始根结点的为0 )
然后将index按从小到大排序
顺序输出结点 就是层序遍历
**/

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std; 
struct Node{
	int index;       //存放结点的下标 
	int val;
};
int n;
vector<Node> node;
vector<int>  post, in;
void pre(int root, int s, int e, int index){       //后 中 ->前 
	if(s > e) return;
	int i = s;
	while(i <= e && in[i] != post[root]) i++;
	node.push_back({index, post[root]});
	pre(root - e - 1 + i, s, i-1, index * 2 + 1);
	pre(root - 1, i + 1, e, index * 2 + 2);
}
bool cmp(Node a, Node b){
		return a.index < b.index;  //a<b升序  根据index按从小到大排序 
} 
int main(){
	scanf("%d", &n);
	post.resize(n);
	in.resize(n);
	for(int i = 0; i < n; i++){
		scanf("%d", &post[i]);
	}
	for(auto i = 0; i < n; i++){
		scanf("%d", &in[i]);
	}
	pre(n-1, 0, n-1, 0);
	sort(node.begin(), node.end(), cmp);  //#algorithm中 
	for(auto i =0; i < node.size(); i++){
		if(i != 0) printf(" ");
		printf("%d", node[i].val);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41698081/article/details/90936858