Advertisement

lesson12-3 使用二叉链表存储二叉树的叶子结点数目

阅读量:

思路1:

直接对这棵二叉树进行遍历操作,以计算其中的叶子节点数量

代码1:

复制代码
 int n=0;

    
 int count(BTNode *t){
    
 	//int n=0;
    
 	if(t){
    
 		if(t->lchild==NULL&&t->rchild==NULL)
    
 			++n;
    
 		count(t->lchild);
    
 		count(t->rchild);
    
 	}
    
 	return n;
    
 }
    
    
    
    

思路2:

首先计算左子树中叶子节点的数量,随后确定右子树中叶子节点的数量,最终将两者的结果相加并返回

代码2:

复制代码
 int count2(BTNode *t){

    
 	int n1,n2;
    
 	if(t==NULL)
    
 		return 0;
    
 	else if(t->lchild==NULL&&t->rchild==NULL)
    
 		return 1;
    
 	else
    
 	{
    
 		n1=count2(t->lchild);
    
 		n2=count2(t->rchild);
    
 		return n1+n2;

全部评论 (0)

还没有任何评论哟~