37
37
<li><code>-1000 <= Node.val <= 1000</code></li>
38
38
</ul >
39
39
40
-
41
40
## 解法
42
41
43
42
<!-- 这里可写通用的实现逻辑 -->
@@ -59,15 +58,13 @@ class Solution:
59
58
def minDepth (self , root : TreeNode) -> int :
60
59
if root is None :
61
60
return 0
62
- if root.left is None and root.right is None :
63
- return 1
64
- l = self .minDepth(root.left)
65
- r = self .minDepth(root.right)
66
- # 如果左子树和右子树其中一个为空,那么需要返回比较大的那个子树的深度
67
- if root.left is None or root.right is None :
68
- return l + r + 1
61
+ # 如果左子树和右子树其中一个为空,那么需要返回比较大的那个子树的深度+1
62
+ if root.left is None :
63
+ return 1 + self .minDepth(root.right)
64
+ if root.right is None :
65
+ return 1 + self .minDepth(root.left)
69
66
# 左右子树都不为空,返回最小深度+1即可
70
- return min (l, r) + 1
67
+ return 1 + min (self .minDepth(root.left), self .minDepth(root.right))
71
68
```
72
69
73
70
### ** Java**
@@ -92,16 +89,51 @@ class Solution:
92
89
*/
93
90
class Solution {
94
91
public int minDepth (TreeNode root ) {
95
- if (root == null ) return 0 ;
96
- if (root. left == null && root. right == null ) return 1 ;
97
- int l = minDepth(root. left);
98
- int r = minDepth(root. right);
99
- if (root. left == null || root. right == null ) return l + r + 1 ;
100
- return Math . min(l, r) + 1 ;
92
+ if (root == null ) {
93
+ return 0 ;
94
+ }
95
+ if (root. left == null ) {
96
+ return 1 + minDepth(root. right);
97
+ }
98
+ if (root. right == null ) {
99
+ return 1 + minDepth(root. left);
100
+ }
101
+ return 1 + Math . min(minDepth(root. left), minDepth(root. right));
101
102
}
102
103
}
103
104
```
104
105
106
+ ### ** C++**
107
+
108
+ ``` cpp
109
+ /* *
110
+ * Definition for a binary tree node.
111
+ * struct TreeNode {
112
+ * int val;
113
+ * TreeNode *left;
114
+ * TreeNode *right;
115
+ * TreeNode() : val(0), left(nullptr), right(nullptr) {}
116
+ * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
117
+ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
118
+ * };
119
+ */
120
+ class Solution {
121
+ public:
122
+ int minDepth(TreeNode* root) {
123
+ if (root == nullptr) {
124
+ return 0;
125
+ }
126
+ if (root->left == nullptr) {
127
+ return 1 + minDepth(root->right);
128
+ }
129
+ if (root->right == nullptr) {
130
+ return 1 + minDepth(root->left);
131
+ }
132
+ return 1 + min(minDepth(root->left), minDepth(root->right));
133
+ }
134
+ };
135
+ ```
136
+
105
137
### **...**
106
138
107
139
```
0 commit comments