计算二叉树的深度和叶子数(递归)


#include <stdio.h>
typedef struct BiTNode
{
	char data;
	struct BiTNode* rchild;
	struct BiTNode* lchild;
}BiTNode;
//计算树的深度
int TreeDepth(BiTNode *root)
{
	int right=0;
	int left=0;
	int deep=0;
	if(root==NULL)
	{
		return deep;
	}
	right=TreeDepth(root->rchild);//计算左子树的深度
	left=TreeDepth(root->lchild);//计算右子树的深度
	deep=right>left?right:left;
	deep++;
	return deep;
}
//计算树的叶子树
int TreeLeaf(BiTNode *root)//这里也可将叶子数传出.int TreeLeaf(BiTNode *root,int *num)
{
	static int num=0;
	if(root==NULL)
	{
		return num;
	}
	if(root->lchild==NULL&&root->rchild==NULL)
	{
		num++;
	}
	TreeLeaf(root->lchild);
	TreeLeaf(root->rchild);
	return num;
}
int main()
{
	int deep=0;
	int num=0;
	BiTNode root={'O',NULL,NULL};
	BiTNode a={'A',NULL,NULL};
	BiTNode b={'B',NULL,NULL};
	BiTNode c={'C',NULL,NULL};
	BiTNode d={'D',NULL,NULL};
	BiTNode e={'E',NULL,NULL};
	root.lchild=&a;
	root.rchild=&b;
	a.lchild=&c;
	a.rchild=&d;
	d.rchild=&e;
	deep=TreeDepth(&root);
	printf("树的深度:%d\n",deep);
	num=TreeLeaf(&root);
	printf("树的叶子数:%d\n",num);
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM