例题-二叉树的深度

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

原理

  • 如果一棵树只有一个结点,它的深度为1。
  • 如果根结点只有左子树而没有右子树,那么树的深度应该是其左子树的深度加1;同样如果根结点只有右子树而没有左子树,那么树的深度应该是其右子树的深度加1。
  • 如果既有右子树又有左子树,那该树的深度就是其左、右子树深度的较大值再加1。
  • 因此用递归更为简便。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class TreeNode
{
public:
int data;
TreeNode* lchild = nullptr;
TreeNode* rchild = nullptr;
TreeNode(int data) :data(data) {};
~TreeNode() {};
};

class Tree
{
public:
int Tree::TreeDepth(TreeNode* pRoot)
{ //二叉树的深度
if (pRoot == nullptr)
return 0;
int lMax = TreeDepth(pRoot->lchild);
int rMax = TreeDepth(pRoot->rchild);
int tMax = (lMax > rMax) ? lMax : rMax;
return tMax + 1;
}
};

输入为

1
[1,2,3,21,22,31,32,211]

输出为

1
4