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 — 二叉树的最大深度-104 · Issue #53 · sl1673495/leetcode-javascript Open Description104.二叉树的最大深度 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: https://leetcode-cn.com/problems/maximum-depth-of-binary-tree 思路DFS简单的 DFS 思路就是递归的遍历整个子树,每递归一个子节点就把传入的 depth 参数 +1,并且去对比全局保存的最大值变量 max 并且更新。 let maxDepth = function (root) { let max = 0 let helper = (node, depth) => { if (!node) return max = 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 } BFSBFS 的思路还是套标准模板,每次循环是一层的分界点,在每轮循环中不停的把下一层的子节点加入到队列中,下次循环则继续处理这些子节点,并且每轮循环都把 max + 1,这样最后的 max 就是最大的深度了。 /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number} */ let maxDepth = function (root) { if (!root) return 0 let max = 0 let queue = [root] while (queue.length) { max += 1 let len = queue.length while (len--) { let node = queue.shift() if (node.left) { queue.push(node.left) } if (node.right) { queue.push(node.right) } } } return max } bobo 老师的解法let maxDepth = function(root) { if (!root) return 0 return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1 }; 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. |