28
28
29
29
## 解法
30
30
31
+ ** 方法一:递归**
32
+
33
+ 我们可以用递归的方法来解决这道题。递归的终止条件是当前节点为空,此时深度为 $0$;如果当前节点不为空,则当前的深度为其左右子树深度的最大值加 $1$,递归计算当前节点的左右子节点的深度,然后返回它们的最大值加 $1$。
34
+
35
+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。最坏情况下,二叉树退化为链表,递归深度达到 $n$,系统使用 $O(n)$ 大小的栈空间。
36
+
31
37
<!-- tabs:start -->
32
38
33
39
### ** Python3**
@@ -48,6 +54,25 @@ class Solution:
48
54
return 1 + max (self .maxDepth(root.left), self .maxDepth(root.right))
49
55
```
50
56
57
+ ``` python
58
+ # Definition for a binary tree node.
59
+ # class TreeNode:
60
+ # def __init__(self, x):
61
+ # self.val = x
62
+ # self.left = None
63
+ # self.right = None
64
+
65
+ class Solution :
66
+ def maxDepth (self , root : TreeNode) -> int :
67
+ def dfs (root ):
68
+ if root is None :
69
+ return 0
70
+ l, r = dfs(root.left), dfs(root.right)
71
+ return 1 + max (l, r)
72
+
73
+ return dfs(root)
74
+ ```
75
+
51
76
### ** Java**
52
77
53
78
``` java
@@ -70,28 +95,6 @@ class Solution {
70
95
}
71
96
```
72
97
73
- ### ** JavaScript**
74
-
75
- ``` js
76
- /**
77
- * Definition for a binary tree node.
78
- * function TreeNode(val) {
79
- * this.val = val;
80
- * this.left = this.right = null;
81
- * }
82
- */
83
- /**
84
- * @param {TreeNode} root
85
- * @return {number}
86
- */
87
- var maxDepth = function (root ) {
88
- if (! root) {
89
- return 0 ;
90
- }
91
- return 1 + Math .max (maxDepth (root .left ), maxDepth (root .right ));
92
- };
93
- ```
94
-
95
98
### ** C++**
96
99
97
100
``` cpp
@@ -127,17 +130,39 @@ public:
127
130
* }
128
131
*/
129
132
func maxDepth(root *TreeNode) int {
130
- if ( root == nil) {
131
- return 0
132
- }
133
- left, right := maxDepth(root.Left), maxDepth(root.Right)
134
- if left > right {
135
- return 1 + left
136
- }
137
- return 1 + right
133
+ if root == nil {
134
+ return 0
135
+ }
136
+ l, r := maxDepth(root.Left), maxDepth(root.Right)
137
+ if l > r {
138
+ return 1 + l
139
+ }
140
+ return 1 + r
138
141
}
139
142
```
140
143
144
+ ### ** JavaScript**
145
+
146
+ ``` js
147
+ /**
148
+ * Definition for a binary tree node.
149
+ * function TreeNode(val) {
150
+ * this.val = val;
151
+ * this.left = this.right = null;
152
+ * }
153
+ */
154
+ /**
155
+ * @param {TreeNode} root
156
+ * @return {number}
157
+ */
158
+ var maxDepth = function (root ) {
159
+ if (! root) {
160
+ return 0 ;
161
+ }
162
+ return 1 + Math .max (maxDepth (root .left ), maxDepth (root .right ));
163
+ };
164
+ ```
165
+
141
166
### ** Rust**
142
167
143
168
``` rust
0 commit comments