Skip to content

Commit 2775eba

Browse files
committed
🐱(tree): 104. 二叉树的最大深度 补充解法
1 parent f1759c6 commit 2775eba

File tree

1 file changed

+64
-2
lines changed

1 file changed

+64
-2
lines changed

docs/data-structure/tree/recursion/README.md

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,71 @@ class Solution:
4141
- [原题链接](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/)
4242
- [详解链接](https://juejin.im/post/5de254ce51882523467752d0)
4343

44-
### 思路
44+
### 自顶向下
45+
46+
<!-- tabs:start -->
47+
48+
#### **Python**
49+
50+
```python
51+
# Definition for a binary tree node.
52+
# class TreeNode:
53+
# def __init__(self, x):
54+
# self.val = x
55+
# self.left = None
56+
# self.right = None
57+
58+
class Solution:
59+
depth = 0
60+
def maxDepth(self, root: TreeNode) -> int:
61+
self.depth = 0
62+
self.handler(root, 1)
63+
return self.depth
64+
65+
def handler(self, root, depth):
66+
if root is None:
67+
return
68+
self.depth = max(self.depth, depth)
69+
self.handler(root.left, depth + 1)
70+
self.handler(root.right, depth + 1)
71+
```
72+
73+
#### **Go**
74+
75+
```go
76+
/**
77+
* Definition for a binary tree node.
78+
* type TreeNode struct {
79+
* Val int
80+
* Left *TreeNode
81+
* Right *TreeNode
82+
* }
83+
*/
84+
85+
var depth int
86+
func maxDepth(root *TreeNode) int {
87+
depth = 0
88+
handler(root, 1)
89+
return depth
90+
}
91+
92+
func handler(root *TreeNode, curDepth int) {
93+
if root == nil {
94+
return
95+
}
96+
if curDepth > depth {
97+
depth = curDepth
98+
}
99+
handler(root.Left, curDepth + 1)
100+
handler(root.Right, curDepth + 1)
101+
}
102+
```
103+
104+
<!-- tabs:end -->
105+
106+
### 自底向上
45107

46-
递归求解~
108+
「自底向上」:我们首先对所有子节点递归地调用函数,然后根据返回值和根节点本身的值得到答案。
47109

48110
取左右子树最大深度值 + 1(1 为到 root 节点的深度)
49111

0 commit comments

Comments
 (0)