欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

求二叉树度为0,1,2的结点个数

程序员文章站 2022-05-16 18:35:59
...
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50


typedef struct BiTNode{
    char data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

BiTree CreateBiTree( ){
    char ch;
    scanf("%c",&ch);
    if(ch=='#') return NULL;
    else{
        BiTree T = (BiTree)malloc(sizeof(BiTNode));
        T -> lchild  = T -> rchild = NULL;
        T->data = ch;
        T->lchild = CreateBiTree();
        T->rchild = CreateBiTree();
        return T;
    }
}
//统计二叉树中度为0的结点个数
int Degree_0(BiTree T){
    if(T==NULL)
        return 0;
    if(T->lchild==NULL&&T->rchild==NULL)
        return Degree_0(T->lchild)+Degree_0(T->rchild)+1;
    else
        return Degree_0(T->lchild)+Degree_0(T->rchild);
}
//统计二叉树中度为1的结点个数
int Degree_1(BiTree T){
    if(T==NULL)
        return 0;
    if((T->lchild==NULL&&T->rchild!=NULL)||(T->lchild!=NULL&&T->rchild==NULL))
        return Degree_1(T->lchild)+Degree_1(T->rchild)+1;
    else
        return Degree_1(T->lchild)+Degree_1(T->rchild);
}
//统计二叉树中度为2的结点个数
int Degree_2(BiTree T){
    if(T==NULL)
        return 0;
    if((T->lchild!=NULL&&T->rchild!=NULL))
        return Degree_2(T->lchild)+Degree_2(T->rchild)+1;
    else
        return Degree_2(T->lchild)+Degree_2(T->rchild);
}