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

Posted on 2016-06-01 11:12  洪爵士  阅读(6289)  评论(0编辑  收藏  举报
#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);
}