#include <bits/stdc++.h>
using namespace std;
typedef struct BiTNode{
int data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
int preF[6]={4,2,1,3,5,6};
int inF[6]={1,2,3,4,6,5};
int posts[7]={2,3,1,5,7,6,4};
int ins[7]={1,2,3,4,5,6,7};
BiTree PreAndInCreateTree(int prel,int prer, int inl,int inr){
if(prel>prer){
return NULL;
}
BiTNode *root;
int index=0;
root=(BiTNode*)malloc(sizeof(BiTNode));
root->data=preF[prel];
int i;
for(i=inl;i<=inr;i++)
{
if(preF[prel]==inF[i]){
index=i;
break;
}
}
root->lchild=PreAndInCreateTree(prel+1,prel+index-inl,inl,index-1);
root->rchild=PreAndInCreateTree(prel+index-inl+1,prer,index+1,inr);
return root;
}
BiTree PostAndInCreateTree(int postl,int postr, int inl,int inr){
if(postl>postr){
return NULL;
}
BiTNode *root;
int index=0;
root=(BiTNode*)malloc(sizeof(BiTNode));
root->data=posts[postr];
for (int i = inl; i <=inr ; ++i) {
if(posts[postr]==ins[i])
{
index =i;
break;
}
}
root->lchild=PostAndInCreateTree(postl,postl+index-inl-1,inl,index-1);
root->rchild=PostAndInCreateTree(postl+index-inl,postr-1,index+1,inr);
return root;
}
void LevelOrder(BiTree T)
{
queue<BiTree> q;
q.push(T);
while (!q.empty()){
BiTNode *tmp =q.front();
q.pop();
cout<<tmp->data;
if(tmp->lchild!=NULL){
q.push(tmp->lchild);
}
if(tmp->rchild!=NULL){
q.push(tmp->rchild);
}
}
}
int main()
{
BiTree tree;
tree=NULL;
tree=PreAndInCreateTree(0,5,0,5);
cout<<"输入为前序加中序遍历,输出他的层序遍历:"<<endl;
LevelOrder(tree);
cout<<endl;
BiTree trees;
trees=NULL;
cout<<"输入为后序加中序遍历,输出他的层序遍历:"<<endl;
trees=PostAndInCreateTree(0,6,0,6);
LevelOrder(trees);
return 0;
}