求二叉树的深度以及叶结点数(c语言实现)

求二叉树的深度

算法思想:用的是递归的思想,从根结点开始往左子树遍历,遍历完左子树再往右子树遍历,遍历到低端,无法向下遍历,此时返回一个0,返回上层栈。最后得到二叉数的深度。

# include <stdio.h>
# include <stdlib.h>
typedef struct BiNode
{
	BiNode *leftchild;
	int data;
	BiNode *rightchild;
}BiNode,*BiTree;
//建立二叉树
void BuildBiTree(BiTree&T)
{
	T=(BiTree)malloc(sizeof(BiNode));
	char ch;
	scanf("%c",&ch);
	if(ch=='#')
		T==NULL;
	else
	{
		T->data=ch;
		BuildBiTree(T->leftchild);
		BuildBiTree(T->rightchild);
	}
}

如果对于上面的代码有疑问的话,可以去看我的另外一篇博客,希望能帮助到大家。编者是大学生,有不对的地方,还请大家一定要指出!!!谢谢^ _ ^
求二叉树的深度

int DepthBiTree(BiTree &T)
{
	int r,l;	//表示左右子树
	if(T==NULL)	//没有结点
		return 0;
	else if(T->leftchild==NULL && T->rightchild==NULL)//没有左右子树
		return 1;
	else
	{
		l=DepthBiTree(T->leftchild);	//递归左子树
		r=DepthBiTree(T->rightchild);	//递归右子树
		if(r>=l)
			return r+1;
		else
			return l+1;
	}
}

求叶结点的个数

这个其实和求深度是差不多的,都是用递归遍历实现,到最底层都是0或者1个结点

int GetLeaf(BiTree &T)
{
	if(T==NULL)
		return 0;
	else if(T->leftchild==NULL&&T->rightchild==NULL)
		return 1;
	else
		return 
		(GetLeaf(T->leftchild)+GetLeaf(T>rightchild));
}

接下来主函数

int main()
{
	BiTree T;
	int d;
	int n;
	printf("请输入数据,'#'不建立子树 ");
	BuildBiTree(T);
	d=DepthTree(T);
	printf("二叉树的深度为:%d\n",d);
	n=GetLeaf(T);
	printf("二叉树的叶结点的个数为:%d\n",n);
	system("system");
	return 0;
}

附上运行截图,有不对的还请大家指正,谢谢!!!
在这里插入图片描述

  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值