/******************************************************************************************************
* @file name: :CompareBinaryTreeDepth
* @brief :採用遞迴的方式來計算二叉樹的深度
* @author :wvjnuhhail@126.com
* @date :2024/05/03
* @version 1.0 :V1.0
* @property :暫無
* @note :None
* CopyRight (c) 2023-2024 wvjnuhhail@126.com All Right Reseverd
******************************************************************************************************/
#include<stdio.h>
#include <stdbool.h>
//定義結構體
typedef struct CompareBinaryTreeDeep
{
//左孩子
struct CompareBinaryTreeDeep* lchild;
//右孩子
struct CompareBinaryTreeDeep* rchild;
}Tnode_t;
/********************************
* funName: BinaryTree_GetDepth
* funtion: 計算二叉樹的深度(遞迴)
* Argument:
* @n1 : 記錄左子樹的深度
* @n2 : 記錄右子樹的深度
* 返回結果: 二叉樹的深度,型別為整型
* 注意事項: None
* 函式作者: wvjnuhhail@126.com
* 建立日期: 2024/05/03
* 修改歷史: None
* 函式版本: V1.0
* ********************************/
int BinaryTree_GetDepth(Tnode_t *root)
{
int n1; //記錄左子樹的深度
int n2; //記錄右子樹的深度
//1.由於採用遞迴函式,首先寫好終止的條件
if(NULL == root)
{
return 0; //若為空樹,返回0
}
else{
//說明是子樹的二叉樹,分別計算左子樹與右子樹,取兩者的最大值
n1 = BinaryTree_GetDepth(root->lchild);
n2 = BinaryTree_GetDepth(root->rchild);
}
//返回值+1:加上根節點所在的層數
return ((n1 > n2)?n1:n2) + 1;
}