# 二叉树的最小深度(111)
# 题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
# 示例
输入:root = [3,9,20,null,null,15,7]
输出:2
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
# 提示
- 树中节点数的范围在 [0, 105] 内
- -1000 <= Node.val <= 1000
# 算法
# 广度优先遍历
使用变量depth
记录当前树的深度,只要广度遍历到一个叶子节点,就返回当前的深度
/**
* 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)
* }
*/
export const minDepth = (root) => {
if (!root) return 0;
const queue = [root];
let depth = 0;
let findNull = false;
while (queue.length) {
const nextRow = [];
depth++;
while (queue.length) {
const curNode = queue.shift();
if (!curNode.left && !curNode.right) findNull = true;
if (curNode.left) nextRow.push(curNode.left);
if (curNode.right) nextRow.push(curNode.right);
}
if (findNull) return depth;
queue.push(...nextRow);
}
};
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
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
# 深度优先遍历
我们在递归中使用变量depLeft
和depRight
来保存当前节点的左孩子和右孩子的深度
递归每次返回左节点和右节点的最小的深度+1
如果当前节点是叶子节点我们直接返回1
如果当前节点中缺少左孩子或者右孩子,我们返回有孩子的那个数的深度,因为只有右孩子的那个子树可能出现叶子节点
/**
* 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)
* }
*/
export const minDepth = (root) => {
if (!root) return 0;
if (!root.left && !root.right) return 1;
const depLeft = minDepth(root.left);
const depRight = minDepth(root.right);
if (!root.left || !root.right) return depLeft + depRight + 1;
return Math.min(depLeft, depRight) + 1;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16