LeetCode 111. Minimum Depth of Binary Tree

Description

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

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:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

Explanation

Use findMinDepth() as helper function.

If the tree is null, the minimum depth would be 0.

If the tree has only the root node, the minimum depth would be 1.

For normal case,  findMinDepth() takes the minimum depth between left and right subtree of the node and plus 1.

Video Tutorial

Java Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        return findMinDepth(root);
    }
    
    private int findMinDepth(TreeNode root) {
        if (root == null) {
            return Integer.MAX_VALUE;
        }
                
        if (root.left == null && root.right == null) {
            return 1;
        }
        
        return Math.min(findMinDepth(root.left), findMinDepth(root.right)) + 1;
    }
}

One Thought to “LeetCode 111. Minimum Depth of Binary Tree”

  1. Can you please explain why we need a helper in this case? And also why it’s important to have one in general when doing recursion. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *