二叉树求深度和叶子数

329 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

6-4 二叉树求深度和叶子数

编写函数计算二叉树的深度以及叶子节点数。二叉树采用二叉链表存储结构

函数接口定义:

int GetDepthOfBiTree ( BiTree T);

int LeafCount(BiTree T);

其中 T是用户传入的参数,表示二叉树根节点的地址。函数须返回二叉树的深度(也称为高度)。

裁判测试程序样例:

//头文件包含

#include<stdlib.h>

#include<stdio.h>

#include<malloc.h>

//函数状态码定义

#define TRUE 1

#define FALSE 0

#define OK 1

#define ERROR 0

#define OVERFLOW -1

#define INFEASIBLE -2

#define NULL 0

typedef int Status;

//二叉链表存储结构定义

typedef int TElemType;

typedef struct BiTNode{

TElemType data;

struct BiTNode  *lchild, *rchild; 

} BiTNode, *BiTree;

//创建二叉树各结点,输入零代表创建空树

//采用递归的思想创建

//递归边界:空树如何创建呢:直接输入0;

//递归关系:非空树的创建问题,可以归结为先创建根节点,输入其数据域值;再创建左子树;最后创建右子树。左右子树递归即可完成创建!

Status CreateBiTree(BiTree &T){

TElemType e;

scanf("%d",&e);

if(e==0)T=NULL;

else{

 T=(BiTree)malloc(sizeof(BiTNode));
 
 if(!T)exit(OVERFLOW);
 
 T->data=e;
 
 CreateBiTree(T->lchild);
 
 CreateBiTree(T->rchild);
 

}

return OK;

}

//下面是需要实现的函数的声明

int GetDepthOfBiTree ( BiTree T);

int LeafCount(BiTree T);

//下面是主函数

int main()

{

BiTree T;

int depth, numberOfLeaves;

CreateBiTree(T);

depth= GetDepthOfBiTree(T);

numberOfLeaves=LeafCount(T);

printf("%d %d\n",depth,numberOfLeaves);

}

/* 请在这里填写答案 */

输入样例:

1 3 0 0 5 7 0 0 0

输出样例:

3 2

int GetDepthOfBiTree ( BiTree T)
{//总的还是递归思想 
	if(T==NULL){
		return 0;
	}
	else {//从开头一直找到最下面的那个节点记该节点深度为1 
	     //那么他的上一个结点就是在他的深度基础上在加1 
	     //但是要注意一种情况 同一层的情况下 
		 //可能左边的节点下面挂着的孩子还挂着一个孩子 就比如说1下面挂着2 2下面还有3
		 //而右边的节点可能只是1挂着2这种情况
		 //这种情况下我们必须找到最大的那个深度然后赋值给这一层
		 //不然就会出错 
		int sum1=GetDepthOfBiTree ( T->lchild );
		int sum2=GetDepthOfBiTree ( T->rchild );
		if(sum1>sum2) return sum1+1;
		else return sum2+1;
	}
}
int LeafCount(BiTree T)
{//叶子就是度为0的点 所以要找既没有左娃又没有右娃的点 也是递归 
	if(T==NULL){
		return 0;
	}
	else if(T->lchild ==NULL&&T->rchild ==NULL){
		return 1;
	}
	else {
		return LeafCount(T->lchild )+LeafCount(T->rchild );
	}
}