#include<bits/stdc++.h>
using namespace std;
typedef struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
} BTree,*BinTree;
BTree *create()
{
int n;
BTree *p;
cin>>n;
if(n==0)
return NULL;
else
{
p=(BTree *)malloc(sizeof(struct tree));
p->data=n;
p->lchild=create();
p->rchild=create();
return p;
}
}
void preorder(BinTree BT)
{
stack<BinTree> p;
if(BT==NULL)
return ;
while(BT!=NULL||!p.empty())
{
while(BT)
{
p.push(BT);
printf("%d ",BT->data);
BT=BT->lchild;
}
BT=p.top();
p.pop();
BT=BT->rchild;
}
}
void inorder(BinTree BT)
{
stack<BinTree> p;
if(BT==NULL)
return ;
while(BT!=NULL||!p.empty())
{
while(BT)
{
p.push(BT);
BT=BT->lchild;
}
BT=p.top();
p.pop();
printf("%d ",BT->data);
BT=BT->rchild;
}
}
void postorder(BinTree T)
{
int flag[20];
stack<BinTree> Stack;
if(!T)
{
return;
}
while(T)
{
Stack.push(T);
flag[Stack.size()]=0;
T=T->lchild;
}
while(!Stack.empty())
{
T=Stack.top();
if(T->rchild && flag[Stack.size()]==0)
{
flag[Stack.size()]=1;
T=T->rchild;
while(T)
{
Stack.push(T);
flag[Stack.size()]=0;
T=T->lchild;
}
}
T=Stack.top();
printf("%d ",T->data);
Stack.pop();
}
}
void levelorder(BinTree BT)
{
int i=0;
int j=0;
BinTree q[100];
BinTree p;
q[i++]=BT;
while(i!=j)
{
p=q[j++];
printf("%d ",p->data);
if(p->lchild)
q[i++]=p->lchild;
if(p->rchild)
q[i++]=p->rchild;
}
}
int main()
{
BinTree t;
t=create();
printf("先序:");
preorder(t);
printf("\n");
printf("中序:");
inorder(t);
printf("\n");
printf("后序:");
postorder(t);
printf("\n");
printf("层序:");
levelorder(t);
return 0;
}