题意
给定一棵二叉树的后序序列和中序序列,输出它的层序序列
注意点
题解
思路:
①读取数据
②根据后序序列和中序序列重建二叉树
③层序遍历二叉树,输出每个结点的值
函数:
①重建二叉树函数create
和算法笔记先序和中序构建的函数类似,注意numLeft的取值
②层序遍历函数layerOrder
queue中的元素应该是指针类型
#include <stdio.h>
#include <queue>
using namespace std;
const int maxn = 35;
//新建结点
struct node {
int data;
node* lchild;
node* rchild;
};
int n, post[maxn], in[maxn];
//根据后序序列和中序序列重建二叉树
node* create(int postL, int postR, int inL, int inR) {
if (postL > postR) {
return NULL;//空树
}
node* root = new node;
root->data = post[postR];//根节点的数据
int k;
for (k = inL; k <= inR; k++) {//在中序序列中查找根节点
if (in[k] == post[postR]) {
break;
}
}
int numLeft = k - inL;
//左子树中序区间为[inL, k-1],左子树后序区间为[postL, postL+numLeft-1]
root->lchild = create(postL, postL+numLeft-1, inL, k-1);
//右子树中序区间为[k+1, inR],右子树后序区间为[postL+numLeft, postR-1]
root->rchild = create(postL+numLeft, postR-1, k+1, inR);
return root;
}
//层序遍历
void layerOrder(node* root) {
queue<node*> q;
q.push(root);
while (!q.empty()) {
node* now = q.front();
q.pop();
//访问结点
if (now != root) printf(" ");
printf("%d", now->data);
//左右孩子入队
if (now->lchild != NULL) q.push(now->lchild);
if (now->rchild != NULL) q.push(now->rchild);
}
}
int main() {
//读入数据
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &post[i]);
}
for (int i = 0; i < n; i++) {
scanf("%d", &in[i]);
}
//根据后序序列和中序序列重建二叉树
node* root = create(0, n-1, 0, n-1);
//层序遍历二叉树
layerOrder(root);
printf("\n");
return 0;
}