Alan Zhan Blog

Live for nothing, or die for something

111. Minimum Depth of Binary Tree

https://leetcode.com/problems/minimum-depth-of-binary-tree/

Easy


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.

Note: A leaf is a node with no children.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 2

Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5

 

Constraints:

  • The number of nodes in the tree is in the range [0, 105].
  • -1000 <= Node.val <= 1000

Problem

Find the shallowest leaf node in the tree — what is its depth?

Approach

This problem is similar to 104 Maximum Depth of Binary Tree. This time, let’s use a different approach — solving it with an iterative (loop-based) method.

In each iteration, we check whether any node at the current level i has both Left and Right children as nil. If so, that’s the minimum depth — return it. If not, push the nodes of that level into a queue and check the next level.

  1. Declare a queue and push the root into it.
  2. Declare a depth variable to track the current depth.
  3. Start a while loop — continue as long as the queue length is not 0.
  4. Pop a node from the queue. Check if both left and right children are nil — if so, return the current depth. If not, push the left and right children into the queue and continue the loop from step 3.

Source Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func minDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }

    depth := 0
    queue := []*TreeNode{root}

    for len(queue) > 0 {
        depth++
        length := len(queue)
        for i := 0; i < length; i++ {
            node := queue[0]
            if node.Left == nil && node.Right == nil {
                return depth
            }

            if node.Left != nil {
                queue = append(queue, node.Left)
            }

            if node.Right != nil {
                queue = append(queue, node.Right)
            }
            queue = queue[1:]
        }
    }

    return depth
}

Closing

Do you have a better or simpler solution?

Feel free to leave a comment on my blog. Your feedback motivates me to keep writing. Thank you for reading, and let’s grow together to become better versions of ourselves.