GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — 二叉树的最小深度-111 · Issue #54 · sl1673495/leetcode-javascript Open Description111.二叉树的最小深度 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明: 叶子节点是指没有子节点的节点。 示例: 思路DFS记录一个最小值 min,每当 DFS 到节点既没有左节点也没有右节点,就更新这个 min 值,整个树遍历完成后返回这个 min 即可。 let minDepth = function (root) { let min = Infinity let helper = (node, depth) => { if (!node) return if (!node.left && !node.right) { min = Math.min(min, depth) return } if (node.left) { helper(node.left, depth + 1) } if (node.right) { helper(node.right, depth + 1) } } helper(root, 1) return min === Infinity ? 0 : min } BFS这题用 BFS 可能可以更快的找到答案,因为 DFS 必须要遍历完整棵树才可以确定结果,但是 BFS 的话由于层级是从低到高慢慢增加的遍历,所以发现某一层的某个节点既没有左节点又没有右节点的话,就可以直接返回当前的层级作为答案了。 let minDepth = function (root) { if (!root) return 0 let depth = 0 let queue = [root] while (queue.length) { depth++ let len = queue.length while (len--) { let node = queue.shift() let left = node.left let right = node.right if (!left && !right) { return depth } if (left) { queue.push(left) } if (right) { queue.push(right) } } } } Activity |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |