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层序
题⽬⼤意:给定⼀棵⼆叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这⾥假设键值都是
互不相等的正整数。
分析:与后序中序转换为前序的代码相仿(⽆须构造⼆叉树再进⾏⼴度优先搜索),只不过加⼀个
变量index,表示当前根结点在⼆叉树中所对应的下标(从0开始),所以进⾏⼀次输出先序的递归的
时候,把节点的index和value放进结构体⾥,再装进容vector⾥,这样在递归完成后, vector中按照
index排序就是层序遍历的顺序。
如何后序和中序转换为先序,参考:https://www.liuchuo.net/archives/2090
#include <cstdio>
#include<iostream>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
const int maxn = 31;
struct node {
int data;
node* lchild;
node* rchild;
};
int pre[maxn], in[maxn], post[maxn]; //先序 中序 后序 存储
int n; //结点总数
node* creat(int postL, int postR, int inL, int inR) {
if (postL > postR)return NULL; //后序序列长度<=0返回
node* root = new node;
root->data = post[postR]; //后序最右为当前的根
int k = inL;
for (k; k <= inR; k++)
if (in[k] == post[postR]) break; //找到中序的根,退出循环
int numLeft = k - inL;
root->lchild = creat(postL, postL + numLeft - 1, inL, k - 1);
root->rchild = creat(postL + numLeft, postR - 1, k + 1, inR);
return root;
}
int num = 1; //输出空格标志位
void BFS(node* root) {
queue<node*>q;
q.push(root);
while (!q.empty()) {
node* node = q.front();
q.pop();
cout << node->data;
if (num != n)cout << " ";
num++;
if (node->lchild != NULL)q.push(node->lchild);
if (node->rchild != NULL)q.push(node->rchild);
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++)
cin >> post[i];
for (int i = 0; i < n; i++)
cin >> in[i];
node* root = creat(0, n - 1, 0, n - 1); //建树
BFS(root); //层序输出(广度优先搜索 )
return 0;
}