数据结构之二叉树的建立与遍历

   计算二叉树的深度时,可以用先分别计算其子树的深度,在通过判断其左右子树深度的大小,大的为其二叉树的深度;二叉树的遍历以及求叶子数详见我的其他同类文章,分类为二叉树。

下面为题目:


下面为具体代码:

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

typedef struct node
{
    char data;
    struct node *lchild,*rchild;
}node,*nodeptr;

char a[55];
int i,count;

struct node *Creat(struct node *T)
{
    T=(struct node *)malloc(sizeof(struct node));
    if(a[i++]==',')T=NULL;
    else
    {
        T->data=a[i-1];
        T->lchild=Creat(T->lchild);
        T->rchild=Creat(T->rchild);

    }
    return T;
}

void ldr(struct node *T)
{//中序遍历二叉树
    if(T)
    {
        ldr(T->lchild);
        printf("%c",T->data);
        ldr(T->rchild);
    }
}

void lrd(struct node *T)
{//后序遍历二叉树
    if(T)
    {
        lrd(T->lchild);
        lrd(T->rchild);
        printf("%c",T->data);
    }
}

int Countleaf(struct node *T)
{//统计叶子节点个数
    if(T)
    {
        if((!T->rchild)&&(!T->lchild))
        {
            count++;
        }
        Countleaf(T->lchild);
        Countleaf(T->rchild);
    }
    return count;
}

int depth(struct node *T)
{
    int de,del,der;//de为一个子树的深度
    //del为这棵树左子树的深度
    //der为这棵树右子树的深度
    if(!T)de=0;
    else
    {
        del=depth(T->lchild);
        der=depth(T->rchild);
        de=1+(del>der?del:der);
    }
    return de;
}

int main()
{
    struct node *T;
    while(~scanf("%s",a))
    {
        i=0;
        count=0;
        T=Creat(T);
        ldr(T);
        printf("\n");
        lrd(T);
        printf("\n");
        printf("%d\n",Countleaf(T));
        printf("%d\n",depth(T));
    }
    return 0;
}

做一个题目就详细分析一个题目的代码,慢慢也就会觉得递归没有那么难了。关键是多练习,世上无难事,只怕有心人,加油!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值