阅读背景:

求二叉树树的高度和叶结点个数

来源:互联网 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct BitNode//结构定义
{
    char data;
    struct BitNode *lchild;
    struct BitNode *rchild;
} BitNode, *BiTree;

void creatBiTree(BiTree &T)//按前序输入建立二叉树
{
    char ch;
    scanf("%c",&ch);
    if (ch == '#')
    {
        T = NULL;
        return;
    }
    else
    {
        T = (BiTree)malloc(sizeof(BitNode));
        T->data = ch;
        creatBiTree(T->lchild);
        creatBiTree(T->rchild);
    }
}
//求二叉树高度,等于根结点到叶结点最长路径加1
int high(BiTree T)
{
    int Lchild,Rchild;
    if(T==NULL)
        return 0;
    Lchild=high(T->lchild);
    Rchild=high(T->rchild);
    return (Lchild>Rchild)?(Lchild+1):(Rchild+1);
}
//求叶结点个数,
int leaf(BiTree T)
{
    int count1,count2;
    if(T==NULL)
        return 0;
    if(T->lchild==NULL&&T->rchild==NULL)
        return 1;
    else
    {
        count1=leaf(T->lchild);
        count2=leaf(T->rchild);
        return count1+count2;
    }
}
int main()
{
    int a,b;
    BiTree tree = NULL;
    creatBiTree(tree);
    a=high(tree);
    b=leaf(tree);
    printf("高为:%d\n",a);
    printf("叶子结点个数为:%d\n",b);
    return 0;
                                                 #include<stdio.h>
#include<stdlib.h>
#include<s



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: