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
题目大意:给出二叉树的后序和中序序列,输出这棵二叉树的层序序列。(所有的二叉树节点的数据都是互不相等的正整数)
分析:根据二叉树的后序和中序序列可以重建二叉树,再对重建好的二叉树进行层序遍历。
#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
#include<queue>
using namespace std;
struct node {//二叉树的存储结构
int data;//数据域
node* lchild;//指向左子树根节点的指针
node* rchild;//指向右子树根节点的指针
};
node* create(int in[], int post[], int inL, int inR, int postL, int postR) {//根据中序序列和后序序列重建二叉树
if (inL>inR) return NULL;//如果后序序列长度小于等于0,直接返回空
node* root = new node;//新建一个节点,用来存放当前二叉树的根节点
root->data = post[postR];//新建节点的数据域为根节点的值
int k;
for (k = inL;k <= inR;k++) {
if (in[k] == post[postR]) {//在中序序列中找到根节点
break;
}
}
int num = k - inL;//左子树的节点个数
//左子树的后序序列区间为[postL,postL+num-1],中序序列区间为[inL,k-1]
root->lchild = create(in, post, inL, k - 1, postL, postL + num - 1);//返回左子树的根节点地址,赋值给root的左指针
//右子树的后序序列区间为[postL+num,postR-1],中序序列区间为[k+1,inR]
root->rchild = create(in, post, k + 1, inR, postL + num, postR - 1);//返回右子树的根节点地址,赋值给root的右指针
return root;//返回根节点地址
}
int n;
int j=0;
void layerorder(node* root) {
queue<node*> q;//存储节点地址的队列
q.push(root);//根节点入队
while (!q.empty()) {
node* now = q.front();
q.pop();//将队首元素出队
cout << now->data;//访问队首元素
j++;
if(j<n) cout<<" ";
if (now->lchild != NULL) q.push(now->lchild);//如果左子树不空,将左子树入队
if (now->rchild != NULL) q.push(now->rchild);//如果右子树不空,将左子树入队
}
}
int main() {
cin >> n;//输入二叉树的节点个数
int *in = new int[n];//new一个变长的int型数组
int *post = new int[n];
for (int i = 0;i < n;i++) {//输入后序序列
cin >> post[i];
}
for (int i = 0;i < n;i++) {//输入中序序列
cin >> in[i];
}
int inL = 0,postL = 0, inR = n - 1, postR = n - 1;
layerorder(create(in, post, inL, inR, postL, postR));
delete[] post;//释放内存空间
delete[] in;
system("pause");
return 0;
}