二叉树

二叉树创建及相关操作

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct BiNode
{
    char data;
    struct BiNode *left,*right;
}node,*bitree;


bitree CREAT()  //先序创建二叉树
{
    char a;
    bitree newnode;
    scanf("%c", &a);
    if(a == '#')
        return NULL;
    else
    {
        newnode = (bitree)malloc(sizeof(node));
        newnode->data = a;
        newnode->left = CREAT();
        newnode->right = CREAT();
    }
    return newnode;
}
void print(bitree p)  //中序输出二叉树
{
    if(p == NULL)
        return;
    else
    {
        print(p->left);
        printf("%c ",p->data);
        print(p->right);
    }
}

int btreedepth(bitree bt)
{
    int ldepth,rdepth;
    if(bt == NULL)
        return 0;
    else
    {
        ldepth = btreedepth(bt->left);
        rdepth = btreedepth(bt->right);
        return (ldepth > rdepth ? ldepth+1 : rdepth+1); //这个位置是可以是它与左右结点的关系。
    }
}

int ncount(bitree bt)
{
    if(bt == NULL)
        return 0;
    else
        return(ncount(bt->left) + ncount(bt->right) + 1);
}

int lcount(bitree bt)
{
    if(bt == NULL)
        return 0;
    else if(bt->left == NULL && bt->right == NULL)
        return 1;
    else
        return (lcount(bt->left) + lcount(bt->right));
}
int main()
{
    bitree route = (bitree)malloc(sizeof(node));
    printf("please input nodes:\n");
    route = CREAT();
    printf("the preorder traversal is:\n");
    print(route);
    printf("\nthe depth of the tree is: %d",btreedepth(route));
    printf("\nthe counts of node is: %d", ncount(route));
    printf("\nthe leaf counts of node is : %d", lcount(route));
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值