求叶子结点个数

发布时间 2023-10-16 19:52:17作者: 依然范德BIAO

递归求叶子结点个数

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

typedef struct node{
    int data;
    struct node *lchild,*rchild;
}TreeNode,*Tree;

void CreateTree(Tree &T)        //先序创建二叉树,中序后序创建和递归遍历一样,只修改位置 
{
    int x;
    scanf("%d",&x);
    if(x==-1)
    {
        T=NULL;
        return;    
    }
    else
    {
        T=(TreeNode*)malloc(sizeof(TreeNode));
        T->data=x;
        printf("输入%d的左结点:",x);
        CreateTree(T->lchild);
        printf("输入%d的右结点:",x);
        CreateTree(T->rchild);
    }
}

int Count(Tree T)
{
    static int count=0;
    if(T==NULL)
        return 0;
    if(T->lchild==NULL&&T->rchild==NULL)
        count++;
        
    Count(T->lchild);
    Count(T->rchild);
    
    return count; 
}

int main()
{
    Tree T;
    CreateTree(T);
    printf("%d ",Count(T)); 
    return 0;    
}