PAT A1020 Tree Traversals 根据后序和中序遍历求得层序遍历
Problem Description
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
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.
每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数N (≤30),二叉树中的结点总数。第二行给出了后序遍历序列,而第三行给出了中序遍历序列。一行中的所有数字都用空格分隔。
Output
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 <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 40;
struct node{
int data;
node* lchild;
node* rchild;
};
int pre[maxn],in[maxn],post[maxn];//先序、中序、后序数组
int n;
node* create(int postL,int postR,int inL,int inR){//根据中序和后序序列得到根节点(生成树)
if(postL > postR)//若后序序列长度小于等于0,则直接返回
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;//左子树的结点个数
//根据后序数组前numLeft个结点和中序数组前numLeft个结点推出左子树的根节点
root->lchild = create(postL,postL+numLeft-1,inL,k-1);
//同理推出右子树的根节点
root->rchild = create(postL+numLeft,postR-1,k+1,inR);
return root;//返回根节点
}
int num = 0;
void BFS(node* root){//利用队列实现层序遍历
queue<node*> q;
q.push(root);
while(!q.empty()){
node* now = q.front();//得到队首元素
q.pop();//出队
printf("%d",now->data);
num++;
if(num < n) printf(" ");
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);
BFS(root);
return 0;
}
参考文献:算法笔记 胡凡