Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 49282a8

Browse files
Create minimum_depth_of_binary_tree.py
1 parent 37bd3ac commit 49282a8

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Problem: Minimum Depth of Binary Tree
2+
# Link: https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
3+
# Tags: Binary Tree, DFS, Recursion, BFS
4+
# Approach: The minimum depth is the length of the shortest root-to-leaf path.
5+
# Use DFS: if one child is None, you must take the other (a missing child
6+
# doesn't form a leaf). Otherwise take 1 + min(leftDepth, rightDepth).
7+
# Time Complexity: O(n)
8+
# Space Complexity: O(h) # h = tree height (recursion stack)
9+
10+
11+
class Solution:
12+
def minDepth(self, root):
13+
if not root:
14+
return 0
15+
16+
# if one child is missing, must go through the other
17+
if not root.left:
18+
return 1 + self.minDepth(root.right)
19+
if not root.right:
20+
return 1 + self.minDepth(root.left)
21+
22+
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /