二叉树的建立

来源:学生作业帮助网 编辑:作业帮 时间:2024/10/04 03:03:51
二叉树的建立
xTj@JTJ񲲴:tQb4"Жa7YdR $M#%B%씒0:1{Q{:Dǟ7tƿ57|,{z,h#ׁ Nׂ@:7eA.ˬˏx:_O|2>]!̾_d'r b9cn"Ǻ#@OtO!STj\.614+X]OylIJdvj ip)hvl>&I*`%8ErL1Dgorv3+q_gx3'7 7)\ ǐ-5M)'PM1UQ 'GQ4FǓ@OFɝXqiA!jUgsQ /b -jkp٬n܆q%ҫI,q5e pĐt+ڹ V]@?-w`c +0VbV, S9K0a5Pxl,m W6kO+r]$*/ <

二叉树的建立
二叉树的建立

二叉树的建立
#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");
}