简繁EN

LeetCodeNo. 031

[LeetCode with Python] 111. Minimum Depth of Binary Tree

Contents

Problem

Problem page: https://leetcode.com/problems/minimum-depth-of-binary-tree/
Topics: Tree, Depth-first Search, Breadth-first Search
Difficulty: Easy
Similar problems: (E) Binary Tree Level Order Traversal, (E) Meeting Rooms, (E) Maximum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.


Analysis

Find the minimum depth of a binary tree. I think there's another problem that asks for the maximum depth of a binary tree. The solutions are pretty similar: recursion with backtracking.
One thing to watch out for: if a node's left subtree has height 2 and its right subtree has height 0, that means the node has no right child. The minimum height of the subtree rooted at that node should be 2+1=3, not 0+1=1.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:

def recurMinDepth(self, root, depth):
if None == root:
return 0
elif None == root.left and None == root.right:
return 1

left_depth = (self.recurMinDepth(root.left, depth) if None != root.left else 0)
right_depth = (self.recurMinDepth(root.right, depth) if None != root.right else 0)

# warn: a node just have a child, a node have two child, their height calculation method are different.
if left_depth > 0 and right_depth > 0:
return min(left_depth, right_depth) + 1;
elif left_depth > 0:
return left_depth + 1
else: # right_depth > 0, or (left_depth == 0 and right_depth == 0)
return right_depth + 1

# @param root, a tree node
# @return an integer
def minDepth(self, root):
return self.recurMinDepth(root, 0)

Article link: https://xnerv.wang/en/leetcode-minimum-depth-of-binary-tree/