作业帮 > 综合 > 作业

二叉树的建立

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/30 14:47:50
二叉树的建立
#define NULL 0
#include "stdio.h"
#include "stdlib.h"
//二叉链表结点定义
struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
};
// 先序建立二叉树
struct tree *create(struct tree *BT,int k)
{
struct tree *p;
int x;
p=(struct tree *)malloc(sizeof(struct tree));
printf("输入结点的整数值(0表示空) :");
scanf("%d",&x);
if(x!=0)
{
if(!(p=(struct tree *)malloc(sizeof(struct tree))))
exit(0);
//生成主根或子树根
p->data=x;
p->lchild=NULL;
p->rchild=NULL;
if(k==0)
BT=p;
if(k==1)
BT->lchild=p;
if(k==2)
BT->rchild=p;
create(p,1);//建立左子树
create(p,2);//建立右子树
}
return(BT);
}
// 先序遍历
int visit(struct tree *BT)
{
if(BT!=NULL)
{
printf("%d ",BT->data);
visit(BT->lchild);
visit(BT->rchild);
}
return 0;
}
void main()
{
struct tree *p;
p=(struct tree *)malloc(sizeof(struct tree));
p=create(p,0);
visit(p);
printf("\n");
}