/* Note:Your choice is C IDE */
#include "stdio.h"
#include<stdlib.h>
typedef struct bitnode
{
char ch;
struct bitnode *lchild,*rchild;
}bitnode,*bittree;
typedef struct stacknode
{
bitnode *data;
struct stacknode *next;
}linkstack;
void initstack(linkstack *s)
{ s->next=NULL; }
void push(linkstack *s,bittree x)
{
linkstack *p;
p=(linkstack *)malloc(sizeof(linkstack));
p->data=x;
p->next=s->next;
s->next=p;
}
bittree pop(linkstack *s)
{
bittree x;
linkstack *p;
p=s->next;
if(s->next==0)return 0;
x=p->data;
s->next=p->next;
free(p);
return x;
}
int emptystack(linkstack *s)
{
if(s->next)return 1;
else return 0;
}
bitnode *gettop(linkstack *s)
{
bittree x;
if(s->next)
x=s->next->data;
return x;
}
bittree cre_tree()
{
bittree root;
char ch;
ch=getchar();
if(ch=='#')root=NULL;
else
{
root=(bittree)malloc(sizeof(bitnode));
root->ch=ch;
root->lchild=cre_tree();
root->rchild=cre_tree();
}
return root;
}
void preorder(bittree root)
{
linkstack s;
bittree p;
initstack(&s);
push(&s,root);
while(emptystack(&s))
{
p=pop(&s);
while(p)
{
printf("%c",p->ch);
if(p->rchild)push(&s,p->rchild);
p=p->lchild;
}
}
}
void inorder(bittree root)
{
bittree p;
linkstack s;
initstack(&s);
p=root;
while(p||emptystack(&s))
//注意还有右子树也要判断
{
while(p)
{
push(&s,p);
p=p->lchild;
}
p=pop(&s);
printf("%c",p->ch);
p=p->rchild;
}
}
void postorder(bittree root)
{
bittree p,q;
linkstack s;
initstack(&s);
p=root;q=NULL;
while(p||emptystack(&s))
{
if(p!=q)
//但p等于root时停止入栈
{
while(p)
{
push(&s,p);
if(p->lchild)p=p->lchild;
//若q的右指针为空或指向刚刚访问过的结点
else p=p->rchild;
}
}
if(!emptystack(&s))break;
q=gettop(&s);
if(q->rchild==p)
{
p=pop(&s);
printf("%c",p->ch);
}
else p=q->rchild;
}
}
void main()
{
bittree root;
root=cre_tree();
preorder(root);printf("\n\n");
inorder(root);printf("\n\n");
postorder(root);printf("\n\n");
}