求叶子结点个数

递归求叶子结点个数

复制代码
#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;    
} 
复制代码

 

posted on   四马路弗洛伊德  阅读(36)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示