Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

111. Minimum Depth of Binary Tree #303

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

111. Minimum Depth of Binary Tree

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

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

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

Example

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

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

Tcdian commented 3 years ago

Solution

/**
 * 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;
    }
    let depth = Infinity;
    if(root.left !== null) {
        depth = Math.min(minDepth(root.left), depth);
    }
    if (root.right !== null) {
        depth = Math.min(minDepth(root.right), depth);
    }
    return depth === Infinity ? 1 : depth + 1;
};
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function minDepth(root: TreeNode | null): number {
    if (root === null) {
        return 0;
    }
    let depth = Infinity;
    if(root.left !== null) {
        depth = Math.min(minDepth(root.left), depth);
    }
    if (root.right !== null) {
        depth = Math.min(minDepth(root.right), depth);
    }
    return depth === Infinity ? 1 : depth + 1;
};