计算二叉树叶子结点个数 C/C++

叶子结点:没有左孩子和右孩子的节点。

如下:

《计算二叉树叶子结点个数 C/C++》

这棵二叉树中叶子结点为红色圈圈中的节点,共有 5 个。

看代码:

#include<iostream>
using namespace std;

typedef struct BinaryTreeNode
{
	char data;  //数据
	struct BinaryTreeNode *left;  //左孩子
	struct BinaryTreeNode *right;  //右孩子
}Node;

int getLeafNum(Node *root)
{
	if (NULL == root)
	{
		return 0;
	}
	if (NULL == root->left && NULL == root->left)
	{
		return 1;
	}

	int leftLeafNum = getLeafNum(root->left);
	int rightLeafNum = getLeafNum(root->right);
	int leafNum = leftLeafNum + rightLeafNum;
	return leafNum;
}

int main()
{
	//准备数据
	Node nodeA = { 'A',NULL,NULL };
	Node nodeB = { 'B',NULL,NULL };
	Node nodeC = { 'C',NULL,NULL };
	Node nodeD = { 'D',NULL,NULL };
	Node nodeE = { 'E',NULL,NULL };
	Node nodeF = { 'F',NULL,NULL };
	Node nodeG = { 'G',NULL,NULL };
	Node nodeH = { 'H',NULL,NULL };
	Node nodeI = { 'I',NULL,NULL };

	//建立关系
	nodeA.left = &nodeB;
	nodeA.right = &nodeC;

	nodeB.left = &nodeD;
	nodeB.right = &nodeE;

	nodeC.left = &nodeF;
	nodeC.right = &nodeG;

	nodeF.left = &nodeH;
	nodeF.right = &nodeI;


	//调用函数
	int depth = getLeafNum(&nodeA);
	printf("二叉树的叶子结点个数为:%d\n", depth);


	system("pause");
	return 0;
}

运行结果:

《计算二叉树叶子结点个数 C/C++》

不保证代码百分百对哈。我也就随便一写。^_^

    原文作者:feel_myself_is_lowB
    原文地址: https://blog.csdn.net/feel_myself_is_lowB/article/details/107101333
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞