原题干:
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
生词:
distinct:明显的,确切的 traversal :遍历
corresponding:对应的
题目大意:
给出二叉树的后序遍历数列和中序遍历数列,输出二叉树的层序遍历数列
其实在昨天的文章中写出了"根据序列还原二叉树"。传送门:C语言-二叉树的遍历-斐斐のBlog
根据这篇文章非常好解这道题。
代码如下:
#include <iostream>
#include <queue>
#include <cstdlib>
using namespace std;
struct node{
int data;
node* lchild;
node* rchild;
};
int post_order[31], in_order[31];
/**
* 找数组数据
* 传入参数:数组地址,想要找的数据
* 传出参数:数据在数组中的下标,找不到则范湖-1
*/
int find_index(const int* arr, int find_data){
for(int i = 0; i < 31; i++)
if(arr[i] == find_data)
return i;
return -1;
}
/**
* 还原二叉树
* 传入参数:后序范围:[post_left, post_right]
* 中序范围:[in_left, in_right]
* 传出:树根地址
*/
node* create(int post_left, int post_right, int in_left, int in_right){
if(post_left > post_right) return NULL;
node* root = (node*)malloc(sizeof(node));
root->data = post_order[post_right];
int root_position_inorder = find_index(in_order, root->data);
int Lchild_sum = root_position_inorder - in_left;
int Lchild_post_left = post_left,
Lchild_post_right = post_left + Lchild_sum - 1,
Lchild_in_left = in_left,
Lchild_in_right = root_position_inorder - 1;
int Rchild_post_left = post_left + Lchild_sum,
Rchild_post_right = post_right - 1,
Rchild_in_left = root_position_inorder + 1,
Rchild_in_right = in_right;
root->lchild = create(Lchild_post_left, Lchild_post_right, Lchild_in_left, Lchild_in_right);
root->rchild = create(Rchild_post_left, Rchild_post_right, Rchild_in_left, Rchild_in_right);
return root;
}
/**
* 广度优先都锁,层序遍历二叉树
* 传入参数:二叉树树根地址,二叉树个数(用来判断是否输出空格)
*/
void BFS(node* root, int sum){
queue<node*> Q;
Q.push(root);
int cnt = 0;
while(!Q.empty()){
node* iterator = Q.front();
Q.pop();
cnt++;
if(cnt < sum) cout << iterator->data << ' ';
else cout << iterator->data;
if(iterator->lchild) Q.push(iterator->lchild);
if(iterator->rchild) Q.push(iterator->rchild);
}
}
int main(){
int cnt;
cin >> cnt;
for(int i = 0; i < cnt; i++)
cin >> post_order[i];
for(int i = 0; i < cnt; i++)
cin >> in_order[i];
node* root = create(0, cnt-1, 0, cnt-1);
BFS(root, cnt);
return 0;
}