当前位置:文档之家› 二叉树的递归算法建立与遍历

二叉树的递归算法建立与遍历

/*定义二叉树节点类型*/

/*(说明:本代码为自己编写,编译的,验证成功的!由于本人编写前,
也在网上找了源码,但是看了几个都不对,要么是伪代码,要不就
是根据伪代码直接译的,根本编译不了。所以特意把本码传到网上
供大家参考,研究)*/

#include
#i一nclude
struct node {
struct node *lchild;
struct node *rchild;
char data;
};

/*建立二叉树*/

struct node *createbt(struct node *t)
{
char num;
printf("pls input a num:\n");
scanf("%c",&num);
getchar();/*易错点一,作用:过滤“回车”字符*/
if(num=='#')
t=NULL;
else
{
t=(struct node *)malloc(sizeof(struct node));
t->data=num;
t->lchild=createbt(t->lchild);\*易错点二,一定要用节点接收,作用:根和子树连接起来*\
t->rchild=createbt(t->rchild);
}
return t;
}

\*先序遍历*\

int inorder(struct node *t)
{
if(t)
{
inorder(t->lchild);
printf("%c ",t->data);
inorder(t->rchild);
}
}

\*中序遍历*\

void postorder(struct node *t)
{
if(t)
{
postorder(t->lchild);
postorder(t->rchild);
printf("%c ",t->data);
}
}

\*后续遍历*\

int preorder(struct node *bt)
{
if(bt!=NULL)
{
printf("%c ",bt->data);
preorder(bt->lchild);
preorder(bt->rchild);
}
return 0;
}

\*主函数*\

int main(void)
{
struct node *p=NULL;
//p=(struct node *)malloc(sizeof(struct node));
printf("pls input some nums:\n");
p=createbt(p);
printf("\n xianxu \n");
preorder(p);
printf("\n zhongxu \n");
inorder(p);
printf("\n houxu \n");
postorder(p);
printf("\n");
}

相关主题
文本预览
相关文档 最新文档