Leetcode 111: Minimum Depth of Binary Tree

grid47
grid47
Exploring patterns and algorithms
Oct 26, 2024 5 min read

A deep tree with soft, glowing light reaching the minimal depth, highlighting the shortest path.
Solution to LeetCode 111: Minimum Depth of Binary Tree Problem

Given a binary tree, find its minimum depth. The minimum depth is defined as the number of nodes along the shortest path from the root node down to the nearest leaf node. A leaf node is a node that does not have any children.
Problem
Approach
Steps
Complexity
Input: The input is a binary tree represented by its root node.
Example: root = [1,null,2,null,3,null,4]
Constraints:
• The number of nodes in the tree is in the range [0, 10^5].
• -1000 <= Node.val <= 1000
Output: The output is the minimum depth of the binary tree, which is the number of nodes along the shortest path from the root to a leaf node.
Example: 5
Constraints:
• The minimum depth is always a positive integer if the tree is non-empty.
Goal: The goal is to find the minimum depth by recursively checking the depth of the left and right subtrees and choosing the minimum of them.
Steps:
• If the tree is empty, return 0.
• Traverse the tree recursively to find the depths of the left and right subtrees.
• If the left or right subtree is NULL, return the depth of the other subtree.
• Return the minimum of the left and right subtree depths plus one to account for the current node.
Goal: Ensure that the solution handles large inputs efficiently.
Steps:
• The algorithm must handle trees with up to 10^5 nodes.
Assumptions:
• The input is a valid binary tree.
Input: Input: root = [10,5,15,null,null,12,20]
Explanation: The tree is balanced and has a minimum depth of 2, as the shortest path from the root to a leaf is from 10 to 15.

Input: Input: root = [1,null,2,null,3,null,4]
Explanation: The tree is a straight line, and the minimum depth is 5, which corresponds to the path from 1 to 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus