Skip to content

111. 二叉树的最小深度 #25

Open
@zpc7

Description

@zpc7

111. 二叉树的最小深度

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function (root) {
    if (root === null) return 0;  // 叶子节点
    if (root.left === null && root.right === null) return 1; //根节点

    // 只有右节点
    if (root.left === null) {
        return minDepth(root.right) + 1;
    }
    // 只有左节点
    if (root.right === null) {
        return minDepth(root.left) + 1;
    }
    // 左右节点都有
    return Math.min(minDepth(root.right), minDepth(root.left)) + 1
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    简单LeetCode 难度定级

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions