Skip to content

Commit 946591d

Browse files
author
杨世超
committed
Update 0104. 二叉树的最大深度.md
1 parent d2c7af4 commit 946591d

File tree

1 file changed

+38
-9
lines changed

1 file changed

+38
-9
lines changed

Solutions/0104. 二叉树的最大深度.md

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,51 @@
55

66
## 题目大意
77

8-
给定一个二叉树,找出其最大深度。
8+
**描述**:给定一个二叉树的根节点 `root`
9+
10+
**要求**:找出该二叉树的最大深度。
11+
12+
**说明**
13+
14+
- 二叉树的深度:根节点到最远叶子节点的最长路径上的节点数。
15+
- 叶子节点:没有子节点的节点。
16+
17+
**示例**
18+
19+
```Python
20+
输入 [3,9,20,null,null,15,7]
21+
对应二叉树
22+
3
23+
/ \
24+
9 20
25+
/ \
26+
15 7
27+
输出 3
28+
解释 该二叉树的最大深度为 3
29+
```
930

1031
## 解题思路
1132

12-
递归遍历,先递归遍历左右子树,返回左右子树的高度,则当前节点的高度为左右子树最大深度+1。即 `max(leftHeight, rightHeight) + 1`
33+
### 思路 1: 递归算法
34+
35+
根据递归三步走策略,写出对应的递归代码。
1336

14-
## 代码
37+
1. 写出递推公式:`当前二叉树的最大深度 = max(当前二叉树左子树的最大深度, 当前二叉树右子树的最大深度) + 1`
38+
- 即:先得到左右子树的高度,在计算当前节点的高度。
39+
2. 明确终止条件:当前二叉树为空。
40+
3. 翻译为递归代码:
41+
1. 定义递归函数:`maxDepth(self, root)` 表示输入参数为二叉树的根节点 `root`,返回结果为该二叉树的最大深度。
42+
2. 书写递归主体:`return max(self.maxDepth(root.left) + self.maxDepth(root.right))`
43+
3. 明确递归终止条件:`if not root: return 0`
44+
45+
### 思路 1:代码
1546

1647
```Python
1748
class Solution:
18-
def maxDepth(self, root: TreeNode) -> int:
19-
if root == None:
49+
def maxDepth(self, root: Optional[TreeNode]) -> int:
50+
if not root:
2051
return 0
21-
22-
leftHeight = self.maxDepth(root.left)
23-
rightHeight = self.maxDepth(root.right)
24-
return max(leftHeight, rightHeight)+1
52+
53+
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
2554
```
2655

0 commit comments

Comments
 (0)