版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CSDN___CSDN/article/details/83755845
该程序使用的是递归地创建方法,以及非递归的遍历算法
运行环境:Dev-C++
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
char data;
struct node *lchild,*rchild;
}bintnode;
typedef struct stack{
bintnode * data[100];
int tag[100];
int top;
}seqstack;
void push(seqstack *s,bintnode * t)
{
s->data[s->top]=t;
s->top++;
}
bintnode* pop(seqstack *s)
{
if(s->top!=0)
{
s->top--;
return (s->data[s->top]);
}
else
{
return NULL;
}
}
bintnode *node;
bintnode *createbintree()
{
char ch;
bintnode *t;
if((ch=getchar())=='#')
{
t=NULL;
}
else
{
t=(bintnode *)malloc(sizeof(bintnode));
t->data=ch;
t->lchild=createbintree();
t->rchild=createbintree();
}
return t;
}
//递归的前序遍历,中序遍历,后序遍历
void preorder(bintnode *t)
{
seqstack s;
s.top=0;
while((t)||(s.top!=0))
{
if(t)
{
printf("%c ",t->data);
push(&s,t);
t=t->lchild;
}
else
{
t=pop(&s);
t=t->rchild;
}
}
}
void inorder(bintnode *t)
{
seqstack s;
s.top=0;
while((t!=NULL) || (s.top!=0))
{
if(t)
{
push(&s,t);
t=t->lchild;
}
else
{
t=pop(&s);
printf("%c ",t->data);
t=t->rchild;
}
}
}
void postorder(bintnode *t)
{
seqstack s;
s.top=0;
while((t)||(s.top!=0))
{
if(t)
{
s.data[s.top]=t;
s.tag[s.top]=0;
s.top++;
t=t->lchild;
}
else
{
if(s.tag[s.top-1]==1)
{
s.top--;
t=s.data[s.top];
printf("%c ",t->data);
t=NULL;
}
else
{
t=s.data[s.top-1];
s.tag[s.top-1]=1;
t=t->rchild;
}
}
}
}
int main ()
{
node = createbintree();
preorder(node);
return 0;
}