#include<iostream>
#include<stdlib.h>
#include<queue>
#define ElemType int
using namespace std;
typedef struct BiTNode{
ElemType data;
struct BiTNode *lchild,*rchild;
}TNode,*Tree;
int treenum[]={1,2,4,0,0,5,0,0,3,0,0};
int k;
void createTree(Tree &T,int &k)
{
ElemType n;
// printf("输入为0停止!\n");
// scanf("%d",&n);
if(treenum[k]==0){
T=NULL;
k++;
}
else{
T=new TNode;
T->data=treenum[k];
k++;
// cout<<"T="<<T->data<<"k="<<k<<endl;
createTree(T->lchild,k);
createTree(T->rchild,k);
}
}
//中序遍历
int InterTree(Tree &T)
{
if(T==NULL){
return 0;
}
else{
InterTree(T->lchild);
cout<<T->data;
InterTree(T->rchild);
}
}
//先序遍历
int PreTree(Tree &T)
{
if(T==NULL){
return 0;
}
else{
cout<<T->data;
PreTree(T->lchild);
PreTree(T->rchild);
}
}
//后序遍历
int PostTree(Tree &T)
{
if(T==NULL){
return 0;
}
else{
PostTree(T->lchild);
PostTree(T->rchild);
cout<<T->data;
}
}
//层序遍历
void LevelOrder(Tree T)
{
if (T==NULL){
return ;
}
queue<Tree> deq; //创建队列
deq.push(T); //将T入队
while(!deq.empty()){ //循环结束条件队列为空
Tree tr = deq.front(); //从队列头开始如果有左孩子或者右孩子就插入,同时队头元素出队
cout<<tr->data;
deq.pop();
if(tr->lchild!=NULL){
deq.push(tr->lchild);
}
if(tr->rchild!=NULL){
deq.push(tr->rchild);
}
}
}
int main()
{
Tree T;
k=0;
createTree(T,k);
cout<<"先序遍历"<<endl;
PreTree(T);
cout<<endl;
cout<<"中序遍历"<<endl;
InterTree(T);
cout<<endl;
cout<<"后序遍历"<<endl;
PostTree(T);
cout<<endl;
cout<<"层序遍历"<<endl;
LevelOrder(T);
cout<<endl;
return 0;
}