代码如下:如果有地方写的不对,或者需要改进的地方,还请大佬指出
#include<stdio.h>
#include<malloc.h>
typedef struct bitnode
{
int data;
struct bitnode *lchild,*rchild;
}bitnode,*bitree;
void visit(bitree t)
{
printf("%d ",t->data);
}
//先序遍历
void xpreorder(bitree t)
{
if(t!=NULL)
{
visit(t);
xpreorder(t->lchild);
xpreorder(t->rchild);
}
}
//中序遍历
void zpreorder(bitree t)
{
if(t!=NULL)
{
zpreorder(t->lchild);
visit(t);
zpreorder(t->rchild);
}
}
//后序遍历
void hpreorder(bitree t)
{
if(t!=NULL)
{
hpreorder(t->lchild);
hpreorder(t->rchild);
visit(t);
}
}
//以上三种遍历算法的时间复杂度都为O(n)。
//先序建立二叉树
void creatbitree(bitree &t)
{
int n;
printf("请输入结点的值;\n");
scanf("%d",&n);
if(n==0)
t=NULL;
else
{
bitree s=(bitnode *)malloc(sizeof(bitnode));
s->data=n;
t=s;
printf("请输入左结点的值,");
creatbitree(t->lchild);
printf("请输入右结点的值,");
creatbitree(t->rchild);
}
}
int main()
{
bitree t;
creatbitree(t);
printf("\n先序遍历:\n");
xpreorder(t);
printf("\n中序遍历:\n");
zpreorder(t);
printf("\n后序遍历:\n");
hpreorder(t);
return 0;
}
代码演示: