#include<stdio.h>
#include<stdlib.h>
typedef char datatype;
typedef struct node
{
datatype data;
struct node *lchild,*rchild;
}bintnode;
typedef bintnode * bintree;
bintree root;
bintree createtree()
{
char ch;
bintree t;
if((ch=getchar())=='#')
{
t=NULL;
}
else
{
t=(bintnode*)malloc(sizeof(bintree));
t->data=ch;
t->lchild=createtree();
t->rchild=createtree();
}
}
typedef struct stack
{
bintree data[100];
int tag[100];
int top;
}seq;
void push(seq *s,bintree t)
{
s->data[s->top]=t;
s->top++;
}
bintree pop(seq *s)
{
if(s->top!=0)
{
s->top--;
return s->data[s->top];
}
else
{
return NULL;
}
}
//非递归前序遍历
void pre(bintree t)
{
seq s;
s.top=0;
while(t||(s.top!=0))
{
if(t)
{
printf("%c",t->data);
push(&s,t);
t=t->lchild;
}
else
{
pop(&s);
t=t->rchild;
}
}
}
//中序遍历
void mid(bintree t)
{
seq s;
s.top=0;
while(t||(s.top=0))
{
if(t)
{
push(&s,t);//入栈
t=t->lchild;//指向左孩子
}
else
{
t=pop(&s);//头结点出栈
printf("%c",t->data);//打印头结点
t=t->rchild; //指向右孩子
}
}
}
//后序遍历
void post(bintree t)
{
seq 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]=0;
t=t->rchild;
}
}
}
C语言实现二叉树遍历
最新推荐文章于 2023-05-08 23:30:40 发布