leetCode打卡——111

202 阅读1分钟

题目

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.

思路

  1. 一棵树的最小高度,等于左右子树的较小高度+1;
  2. 当左右子树有且仅有一个为0的高度,那么该树的较小高度也只能取不为0的子树高度+1
var minDepth = function(root) {
    return run(root)
};
var run = function(node) {
    if (!node) {
        return 0;
    }
    var leftH = run(node.left)
    var rightH = run(node.right)

    if (
        !(leftH === 0 && rightH === 0) &&
        (leftH === 0 || rightH === 0)
    ) {
        return Math.max(leftH, rightH) + 1;
    } else {
        return Math.min(leftH, rightH) + 1;
    }
}