111. Minimum Depth of Binary Tree

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.

Analyze

Way1: recursive

陷阱: 需注意的是其中一个子节点为空, 另外一个子节点不为空, 需要以不为空的子节点那边来计数。比如

    0
   / \
  1  null

此时最短路径为 2 而不是 1。

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *   this.val = val;
 *   this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function(root) {
  if (!root) return 0
  const leftRootMinDepth = minDepth(root.left)
  const rightRootMinDepth = minDepth(root.right)
  if (leftRootMinDepth === 0 || rightRootMinDepth === 0) {
    return Math.max(leftRootMinDepth, rightRootMinDepth) + 1
  }
  return Math.min(leftRootMinDepth, rightRootMinDepth) + 1
};

Sister title

104