C语言数据结构之二叉树部分(2)

二叉树的应用

#include <stdio.h>
#include <stdlib.h>
typedef struct node 
{
    int data;
    struct node *left,*right;
}BTNode;
BTNode *CreateBTree(int a[],int n);//创建
int LeafCount(BTNode *root);//找叶子
int HeightBTree(BTNode *root);//找层数
void MirrorBTree(BTNode *root);//镜像
int  main()
{
    int i,j;
    BTNode *root;
    int a[8] = {3,2,5,8,4,7,6,9};
    //二叉树的创建
    root = CreateBTree(a,8);
    //叶子节点的个数
    i = LeafCount(root);
    printf("叶子节点个数是:%d \n",i);
    //返回层数
    j = HeightBTree(root);
    printf("二叉树的高度为:%d \n",j);

    return 0;
}
//创建
BTNode *CreateBTree(int a[],int n)
{
    BTNode *p,*pa,*c,*root;
    int i;
    root = (BTNode *)malloc(sizeof(BTNode));
    root->data = a[0];
    root->left = root->right = NULL;
    for(i  = 1;i < n;i++)
    {
        p = (BTNode *)malloc(sizeof(BTNode));
        p->data = a[i];
        p->left = p->right = NULL;
        c = root;
        while(c)
        {
            pa = c;
            if(c->data > pa->data)
            {
                c = c->left;
            }
            else
            {
                c = c->right;
            }
        }
        if(pa->data > p->data)
        {
            pa->left = p;
        }
        else
        {
            pa->right = p;
        }
    }
    return root;
}
//找叶子
int LeafCount(BTNode *root)
{
    int s1,s2,s;
    if(root == NULL)
    {
        s = 0;
    }
    else
    {
        s1 = LeafCount(root->left);
        s2 = LeafCount(root->right);
        s = s1 + s2 +(!root->left && !root->right);
    }
    return s;
}
//找层数
int HeightBTree(BTNode *root)
{
    int s1,s2,s = 0;
    if(root)
    {
        s1 = HeightBTree(root->left);
        s2 = HeightBTree(root->right);
        /*if(s1 > s2)
        {
            s = s1 +1;
        }
        else
        {
            s = s2 + 1;
        }*/
        s = (s1 > s2) ? (s1+1):(s2 +1);
    }
    return s;
}
//镜像
void MirrorBTree(BTNode *root)
{
    BTNode *t;
    if(root)
    {
        MirrorBTree(root->left);
        MirrorBTree(root->right);
        t = root->left;
        root->left = root->right;
        root->right = t;
        /*
        t = root->left;
        root->left = root->right;
        root->right = t;
        MirrorBTree(root->left);
        MirrorBTree(root->right);
        */
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值