↓Skip to main content
  1. LeetCode/

LeetCode 111: Minimum Depth of Binary Tree

·1 min· ·
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-16

  • Submissions: Wrong Answer → Accepted ×3 → Runtime Error → Accepted ×2

Approach
#

Unlike maximum depth, when only one child exists the empty side is not a leaf and cannot count (Tree Template 1):

  • Empty tree: 0.
  • Leaf: 1.
  • One child: 1 + that side’s minimum depth.
  • Both children: 1 + the smaller of the two.

My Attempts
#

Attempt 1 wrote min(left, right) + 1, treating the empty side (depth 0) as the minimum when only one child exists. For [3, 3] (left child only) the answer is 2; it returned 1.

Solution
#

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        if not root.left or not root.right:
            return 1 + self.minDepth(root.left or root.right)
        return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

Complexity
#

Time O(n), space O(h). A BFS that stops at the first leaf is faster in practice.

Mistakes to Avoid
#

  • With one child missing, the empty side has depth 0 but is not a leaf.

Interview Explanation
#

Minimum depth must reach a leaf: with one child only that side counts, and with both I take the smaller; recursion handles the three cases. Time O(n).

Related

LeetCode 112: Path Sum
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 112 note: subtract each value from targetSum on the way down; it works if the remainder matches at a leaf
LeetCode 100: Same Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 note: two empty trees are equal, one empty and one not differ, and otherwise compare values and recurse on both sides
LeetCode 101: Symmetric Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 101 note: the left and right subtrees must mirror each other, outer with outer and inner with inner; compare values, not node objects
LeetCode 104: Maximum Depth of Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 104 note: depth is 1 plus the larger subtree depth, with 0 for an empty tree
LeetCode 110: Balanced Binary Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 110 note: every node’s subtree heights must differ by at most 1; return heights in post-order and propagate -1 once unbalanced
LeetCode 144: Binary Tree Preorder Traversal
·1 min
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 144 note: iterative pre-order traversal records on pop and pushes the right child before the left so the left is handled first