|
| 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