# 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) return 0;

  if (!root.left && !root.right) return 1;

  let dp = Infinity;

  if (root.left) dp = Math.min(dp, minDepth(root.left));
  if (root.right) dp = Math.min(dp, minDepth(root.right));
  return dp + 1;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 广度优先遍历

/**
 * 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) return 0;
  let q = [root];
  let dp = 1;
  while (q.length) {
    let t = [];
    while (q.length) {
      let node = q.shift();
      if (!node.left && !node.right) return dp;
      if (node.left) t.push(node.left);
      if (node.right) t.push(node.right);
    }
    q = t;
    dp++;
  }
  return dp;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29