统计二叉树中叶子结点个数

7 篇文章 0 订阅
#include<stdio.h>
#include<stdlib.h>

typedef char ElemType;
typedef struct BTNode
{
	ElemType data;
	struct BTNode *left;
	struct BTNode *right;
}BTNode,*BiTree;

//创建二叉树
void createBTNode(BiTree &BT)
{
	ElemType ch;
	scanf("%c",&ch);
	if(ch==' ')
		BT=NULL;
	else
	{
		BT = (BTNode*)malloc(sizeof(BTNode));
		BT->data= ch;
		createBTNode(BT->left);
		createBTNode(BT->right);
	}
}

//先序遍历二叉树
void printDLR(BiTree BT)
{
	if(BT)
	{
		printf("%c ",BT->data);
		printDLR(BT->left);
		printDLR(BT->right);
	}
}

//统计二叉树结点个数
void countLeaves(BiTree BT,int &count)
{
	if(BT)
	{
		if(BT->left==NULL && BT->right==NULL)
		count++;
		else{
			countLeaves(BT->left,count);
			countLeaves(BT->right,count);
		}
	}
}

void main()
{
	BTNode *BT;
	int count=0;
	createBTNode(BT);
	printf("先序遍历:");
	printDLR(BT);
	printf("\n");
	countLeaves(BT,count);
	printf("二叉树结点的个数:%d\n",count);
}

按照先序遍历的方式来输入二叉树结点,若孩子结点为空,则输入空格。

输入:

ABD  E  CF

返回结果:

先序遍历:A B D E C F

二叉树结点的个数:3

叶子结点分别是:D、E、F

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是用C语言实现先序遍历序列建立二叉树的代码: ```c #include <stdio.h> #include <stdlib.h> // 定义二叉树的结构体 typedef struct TreeNode { char data; // 数据域 struct TreeNode* leftChild; // 左子树指针 struct TreeNode* rightChild; // 右子树指针 } TreeNode; // 先序遍历序列建立二叉树 TreeNode* buildTree() { char c; scanf("%c", &c); if (c == '#') { return NULL; } TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); root->data = c; root->leftChild = buildTree(); root->rightChild = buildTree(); return root; } // 统计二叉树叶子结点个数 int countLeaves(TreeNode* root) { if (root == NULL) { return 0; } if (root->leftChild == NULL && root->rightChild == NULL) { return 1; } return countLeaves(root->leftChild) + countLeaves(root->rightChild); } // 计算二叉树的深度 int calcDepth(TreeNode* root) { if (root == NULL) { return 0; } int leftDepth = calcDepth(root->leftChild); int rightDepth = calcDepth(root->rightChild); return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1; } int main() { printf("请输入先序遍历序列:"); TreeNode* root = buildTree(); printf("二叉树叶子结点个数:%d\n", countLeaves(root)); printf("二叉树的深度:%d\n", calcDepth(root)); return 0; } ``` 这里采用了递归的方式实现了先序遍历序列建立二叉树统计二叉树叶子结点个数和计算二叉树的深度。其,函数`countLeaves()`用于统计二叉树叶子结点个数,函数`calcDepth()`用于计算二叉树的深度。 运行结果如下: ``` 请输入先序遍历序列:AB#D##CE### 二叉树叶子结点个数:3 二叉树的深度:3 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值