建立二叉树

    先序建立二叉树,树的节点用一个结构体来表示,结构体包含三个元素,节点的值,指向节点左右子数的结构体指针,如下所示。

  4 typedef struct Btree{
  5     int value;
  6     struct Btree *lchild;
  7     struct Btree *rchild;
  8 }*Btree,BtreeNode;

    有了树的节点,我们就可以利用递归建立一个二叉树,函数体如下。

  9 Btree ConstructionBtree(){
 10     int nvalue;
 11     Btree root;
 12     scanf("%d",&nvalue);
 13     if(nvalue == 0)
 14             root = NULL;
 15     else {
 16         root = (Btree)malloc(sizeof(BtreeNode));
 17         root->value = nvalue;
 18         root->lchild = ConstructionBtree();
 19         root->rchild = ConstructionBtree();
 20     }
 21     return root;
 22 }

    这里循环输入根节点的值,如果值为0则表示该子树为空,建立过后先序打印整个树,程序如下

 23 void PreOrderPrintf(Btree T){
 24     if(T == NULL)
 25             return ;
 26     printf("%d ",T->value);
 27     PreOrderPrintf(T->lchild);
 28     PreOrderPrintf(T->rchild);
 29 }

    下面是main函数

 30 int main(){
 31     Btree T;
 32     printf("Please input the value of Btree,0 is the end:\n");
 33     T = ConstructionBtree();
 34     printf("The PreOrder of Btree is:\n");
 35     PreOrderPrintf(T);
 36     printf("\n");
 37     return 0;
 38 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值