给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点
输入: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
const minDepth = (root) => {if (root == null) return 0; // 递归到null节点,返回高度0if (root.left && root.right) { // 左右子树都存在,当前节点的高度1+左右子树递归结果的较小值return 1 + Math.min(minDepth(root.left), minDepth(root.right));} else if (root.left) { // 左子树存在,右子树不存在return 1 + minDepth(root.left);} else if (root.right) { // 右子树存在,左子树不存在return 1 + minDepth(root.right);} else { // 左右子树都不存在,光是当前节点的高度1return 1;}};
BFS
const minDepth = (root) => {if (root == null) return 0;const queue = [root]; // 根节点入列let depth = 1; // 当前层的深度while (queue.length) {const levelSize = queue.length; // 当前层的节点个数let i = 0for (; i < levelSize; i++) { // 遍历 逐个出列const node = queue.shift(); // 出列// 如果没有孩子,直接返回所在层数if (node.left == null && node.right == null) {return depth;}if (node.left) queue.push(node.left); // 有孩子,让孩子入列if (node.right) queue.push(node.right);}depth++; // 肯定有下一层,如果没有早就return了}};
