[
tree
recursion
]
Leetcode 0111. Minimum Depth of Binary Tree
https://leetcode.com/problems/minimum-depth-of-binary-tree
All we need to do in this problem is traverse our graph with dfs or bfs and collect information about nodes depths. Let us use axuilary function dfs
and:
- If we reached
None
, then we return infinity. - If we reached leaf, then we return
1
, depth of our leaf - Finally, for node we return minumum of its children depths plus
1
. Note, that if one of the children is not exist, then is value for its depth will be infinity, so in fact we consider only existing children.
Complexity: time complexity is O(n)
, space complexity is O(h)
.
PS Do not be afraid, that this code is only faster than 5%
of submissions: the reason is that tests were updated resently and results of time distributions are not relevant.
class Solution:
def minDepth(self, root):
def dfs(node):
if not node: return float("inf")
if not node.left and not node.right: return 1
return min(dfs(node.left), dfs(node.right)) + 1
res = dfs(root)
return res if res != float("inf") else 0
If you like the solution, you can upvote it on leetcode discussion section: Problem 0111