LeetCode 111. Minimum Depth of Binary Tree 二叉树的最小深度

题目

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.

讲解

建造一个findMinDepth() 的辅助函数。

如果tree为null, 则最小深度为0。

如果二叉树只有一个根节点,则最小深度为1.

对于其他情况,findMinDepth() 取节点左右子树中的较小深度加上1。

视频教学

Java参考代码

/**
 * 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;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注