二叉树的遍历

来源:互联网 发布:淘宝网图书人性的弱点 编辑:程序博客网 时间:2024/06/05 14:43

本代码采用前序方式创建二叉树,用递归的方式和非递归两种方式输出二叉树,其中递归最好理解,但是它的资源消耗更大,因为你总是不断调用函数。而非递归方式消耗最少,但是相对难以理解,最好自己先创建一个简单二叉树,自己慢慢推。其中前序和中序只是改变一下输出,但后序不一样。后序需要定一个标志确定节点的左子树是否访问完。详细见代码。

#include<stdio.h>

#include<stdlib.h>


typedef char datatype;


typedef struct node{
datatype  data ;
struct node *lchild,*rchild;
struct node *parent;
}bintnode;
typedef bintnode *bintree;


//bintree root;


typedef struct stack //栈的结构体
{
bintree data[100];
int tag[100]; //用于后序输出1表示该节点的左子树已经访问完毕,否则为0;
int top;
}seqstack;


void push(seqstack *s , bintree t)//进栈
{
s->data[s->top]=t ;
s->top++;
}
bintree pop(seqstack *s)//出栈
{
if(s->top!=0)
{
s->top--;
return (s->data[s->top]);
}
else
return NULL;
}
bintree creattree()//前序创建二叉树
{
char p;
bintree T;         //根节点
scanf("%c", &p);
if(p=='0')
{
T=NULL;
}
else{
T=(bintnode *)malloc(sizeof(bintnode));
T->data=p;
T->lchild=creattree();
T->rchild=creattree();
}
return T;
}
void preorder(bintree t)   //前序遍历
{
if(t)
{
printf("%c ",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}


void inorder(bintree t)    //中序
{
seqstack s;
s.top=0;
while((t!=NULL)||(s.top!=0))
{
if(t)
{
//printf("%c  ",t->data);前序时采用这句
push(&s , t);
t=t->lchild;
}
else{
t = pop(&s);
printf("%c ",t->data);
t=t->rchild;
}
}
printf("\n");
}
void outorder(bintree t)    //后序
{
seqstack s;
s.top=0;
while((t!=NULL)||(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)//1表示左子树访问结束
{
s.top--; //top此时指向右子树,所以要-1;
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 ;
}
}
printf("\n");
}
int main()
{
bintree T;
T= creattree();


printf("递归前序\n");
preorder(T);
printf("\n");
printf("非递归中序\n");
inorder(T);
printf("非递归后序\n");
outorder(T);
return 0;
}











0 0
原创粉丝点击