二叉树的深度

二叉树的数据结构如下:

1 struct BinaryTreeNode
2 {
3     int nData;
4 
5     BinaryTreeNode *pLeft;
6     BinaryTreeNode *pRight;
7 };

想要获取二叉树的深度只需先分别取得其左右子树深度的最大值再加1即为这颗二叉树的深度,而求其左右子树的深度也可以这样做,因而可以很快写出递归代码:

 1 int GetDeepth(BinaryTreeNode *root)
 2 {
 3     if (NULL == root)
 4     {
 5         // 空二叉树深度为0
 6         return (0);
 7     }
 8 
 9     // 还是那句话,理解递归算法就是要相信它能完成给它假设的任务
10     // 这里假设LeftDeepth获得了root左子树的深度
11     int LeftDeepth = GetDeepth (root->pLeft);
12 
13     // RightDeepth获得了root右子树的深度
14     int RightDeepth = GetDeepth (root->pRight);
15 
16     // 左右子树深度的最大值再加上root这一层就是以root为根的二叉树的深度
17     return (LeftDeepth > RightDeepth ? (LeftDeepth + 1) : (RightDeepth + 1));
18 }
原文地址:https://www.cnblogs.com/ldjhust/p/3051627.html