Skip to content

Commit 81f2e27

Browse files
committed
Sync LeetCode submission Runtime - 663 ms (5.14%), Memory - 57 MB (9.68%)
1 parent 03d21ca commit 81f2e27

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<p>Given a binary tree, find its minimum depth.</p>
2+
3+
<p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p>
4+
5+
<p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" style="width: 432px; height: 302px;" />
10+
<pre>
11+
<strong>Input:</strong> root = [3,9,20,null,null,15,7]
12+
<strong>Output:</strong> 2
13+
</pre>
14+
15+
<p><strong class="example">Example 2:</strong></p>
16+
17+
<pre>
18+
<strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6]
19+
<strong>Output:</strong> 5
20+
</pre>
21+
22+
<p>&nbsp;</p>
23+
<p><strong>Constraints:</strong></p>
24+
25+
<ul>
26+
<li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li>
27+
<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>
28+
</ul>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Approach 1: Depth First Search
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
# Definition for a binary tree node.
7+
# class TreeNode:
8+
# def __init__(self, val=0, left=None, right=None):
9+
# self.val = val
10+
# self.left = left
11+
# self.right = right
12+
13+
class Solution:
14+
def minDepth(self, root: Optional[TreeNode]) -> int:
15+
if not root:
16+
return 0
17+
18+
left = self.minDepth(root.left)
19+
right = self.minDepth(root.right)
20+
21+
if root.left and root.right:
22+
return 1 + min(left, right)
23+
24+
return 1 + max(left, right)

0 commit comments

Comments
 (0)