Skip to content
On this page

111. 二叉树的最小深度

原题链接:LeetCode 111. 二叉树的最小深度

题目描述

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

**说明:**叶子节点是指没有子节点的节点。

示例 1:

**输入:**root = [3,9,20,null,null,15,7] **输出:**2

示例 2:

**输入:**root = [2,null,3,null,4,null,5,null,6] **输出:**5

提示:

树中节点数的范围在 [0, 105] 内
-1000

难度: Easy


题解代码

javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */

// 叶子节点的定义是左孩子和右孩子都为 null 时叫做叶子节点
// 当 root 节点左右孩子都为空时,返回 1
// 当 root 节点左右孩子有一个为空时,返回不为空的孩子节点的深度
// 当 root 节点左右孩子都不为空时,返回左右孩子较小深度的节点值


var minDepth = function(root) {
    if(!root) {
        return 0
    }
    if (root.left == null && root.right != null) {
        return minDepth(root.right) + 1;
    }
    if (root.right == null && root.left != null) {
        return minDepth(root.left) + 1;
    }
    return Math.min(minDepth(root.left), minDepth(root.right)) + 1
};

技术文档集合