111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
:::info
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
:::
思路
1. DFS
记录一个最小值,同时在递归过程中记录深度,然后当 DFS 到该节点为叶子节点时,更新min。
当整棵树遍历完毕后,返回min即可。
var minDepth = function(root) {let min = Infinity;const dfs = (root, depth) => {if (!root) return;if (!root.left && !root.right) {min = Math.min(min, depth);return;}if (root.left) {dfs(root.left, depth+1);}if (root.right) {dfs(root.right, depth+1);}}dfs(root, 1)return min === Infinity ? 0 : min};
2. BFS
采用 BFS,从低到高逐个层级去遍历树,当发现某一层的某个节点为叶子节点时,直接返回当前层级即可。
var minDepth = function(root) {let depth = 0;if (!root) return depth;const queue = [root];while (queue.length) {const len = queue.length;depth++;for (let i = 0; i < len; i++) {const node = queue.shift();if (!node.left && !node.right) {return depth;}if (node.left) {queue.push(node.left);}if (node.right) {queue.push(node.right);}}}};
104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],3/ \9 20/ \15 7返回它的最大深度 3 。
思路
具体的思路与上述的 二叉树的最小深度 相似,这里就不赘述了。
1. DFS
let maxDepth = function (root) {let max = 0let helper = (node, depth) => {if (!node) returnmax = Math.max(max, depth)if (node.left) {helper(node.left, depth + 1)}if (node.right) {helper(node.right, depth + 1)}}helper(root, 1)return max}
2. BFS
let maxDepth = function (root) {if (!root) return 0let max = 0let queue = [root]while (queue.length) {max += 1let len = queue.lengthwhile (len--) {let node = queue.shift()if (node.left) {queue.push(node.left)}if (node.right) {queue.push(node.right)}}}return max}
解法三
let maxDepth = function(root) {if (!root) return 0return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1};
