The problem requires us to find the minimum depth of a binary tree. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
Return its minimum depth = 2.
0
.val
, left
, and right
.None
, return 0
as this does not contribute to the depth.None
), return 1
.None
, ignore it and return the depth of the non-None
subtree.1
for the current node.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def minDepth(root: TreeNode) -> int:
if not root:
return 0
# If left subtree is None, then the minimum depth must be found in the right subtree
if not root.left:
return minDepth(root.right) + 1
# If right subtree is None, then the minimum depth must be found in the left subtree
if not root.right:
return minDepth(root.left) + 1
# If both subtree exists, find the minimal path from both subtrees
return min(minDepth(root.left), minDepth(root.right)) + 1
N
is the number of nodes in the binary tree. This is because in the worst case, the algorithm will visit each node once.H
is the height of the tree. This is due to the recursion stack used during the depth-first traversal. In the worst-case scenario of a skewed tree, this could be O(N)
.Feel free to ask if you need further clarifications or assistance!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?