题目描述
给定一个树的先序和中序的遍历结果,构建一棵树,并输出这个棵树的层序遍历和后序遍历结果。注:这棵树的结点是由整数描述
输入
树结点总数m
先序输出序列
中序输出序列
输出
层序输出序列
后续输出序列
样例输入
10
1 2 5 10 3 6 13 7 14 15
2 10 5 1 6 13 3 14 7 15
样例输入
1 2 3 5 6 7 10 13 14 15
10 5 2 13 6 14 15 7 3 1
显而易见,我们可以知道,已知中序序列和任意一个前后序序列可以重新构建二叉树。自己画图好好想想就懂,想不明白看书本207页。
//应黄某某要求加入注释思路
#include <iostream>
#include <queue>
using namespace std;
struct binTreeNode
{
int data;
binTreeNode *leftchild;
binTreeNode *rightchild;
binTreeNode()
{
leftchild=NULL;
rightchild=NULL;
}
};
//这里是难点,用给定的前序遍历和中序遍历序列,构造树
//详细讲解见课本p208页,懂得都懂
binTreeNode * creatTree(int *VLR,int *LVR,int n)
{
if(n==0) return NULL;
int k=0;
while(VLR[0]!=LVR[k]) k++;
binTreeNode *t =new binTreeNode();
t->data=LVR[k];
t->leftchild=creatTree(VLR+1,LVR,k);
t->rightchild=creatTree(VLR+k+1,LVR+k+1,n-k-1);
return t;
}
//层序遍历算法,懂得都懂
//用了队列,very简单
void layerOrder(binTreeNode *t)
{
queue <binTreeNode *> Tree;
Tree.push(t);
while(!Tree.empty())
{
binTreeNode *father;
father=Tree.front();
cout <<father->data<<" ";
Tree.pop();
if(father->leftchild!=NULL)
Tree.push(father->leftchild);
if(father->rightchild!=NULL)
Tree.push(father->rightchild);
}
}
//后序遍历算法,懂得都懂
//用递归,very简单
void postOrder(binTreeNode *t)
{
if(t!=NULL)
{
postOrder(t->leftchild);
postOrder(t->rightchild);
cout<<t->data<<" ";
}
}
int main()
{
int * VLR;
int * LVR;
int n;
cin>>n;
VLR =new int [n];
LVR =new int [n];
for(int i =0; i<n; i++)
{
cin>>VLR[i];
}
for(int i =0; i<n; i++)
{
cin>>LVR[i];
}
binTreeNode * root;
root=creatTree(VLR,LVR,n);
layerOrder(root);
cout<<endl;
postOrder(root);
}