统计二叉树的叶子结点个数(C语言数据结构)

一、输入格式

输入二叉树的先序序列。
提示:一棵二叉树的先序序列是一个字符串,若字符是‘#’,表示该二叉树是空树,否则该字符是相应结点的数据元素。

二、输出格式

二叉树的叶子结点个数。

三、源码实现

★简要思路:二叉树结构体(左右结点)—>先序序列建立二叉树—>统计二叉树的叶子结点个数,然后借助主函数来展开调用实现。

#include <stdio.h>
#include<stdlib.h>
int count = 0;
//二叉树结构体
typedef struct BiTNode
{
    
    
    char data;
    struct BiTNode* lchild, * rchild;
}BiTNode, * BiTree;
//先序序列建立二叉树 
int BuildBiTree(BiTree *T)
{
    
    
    char ch;
    scanf_s("%c", &ch);
    if (ch == '#')
        *T = NULL;
    else
    {
    
    
        *T = (BiTNode*)malloc(sizeof(BiTNode));
        (*T)->data = ch;
        BuildBiTree(&(*T)->lchild);
        BuildBiTree(&(*T)->rchild);
    }
    return 1;
}

//统计二叉树的叶子结点个数
int LeafNumber(BiTree *T)
{
    
    
  
    if((*T)!=NULL)
	{
    
    
	        if((*T)->lchild==NULL&&(*T)->rchild==NULL)
	            count++;
	        count=LeafNumber(&(*T)->lchild);
	        count=LeafNumber(&(*T)->rchild);
	}
	return count;
    
    
}
//主函数
int main()
{
    
    
	BiTree T;
	if( BuildBiTree(&T) )
	{
    
    
		printf("%d", LeafNumber(&T));
	}
	printf("\n");
	return 0;
}

四、样例测试

①输入样例
ABC##DE#G##F###
②输出样例
3
③实际测试
ABC##DE#G##F###
3

--------------------------------
Process exited after 2.155 seconds with return value 0
请按任意键继续. . .

2022.5.7记录:Code_流苏(CSDN)
如有任何疑问,评论回复,看到即回,欢迎大家多多交流学习!

猜你喜欢

转载自blog.csdn.net/qq_51646682/article/details/124641004