We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Difficulty: 中等
Related Topics: 树, 深度优先搜索, 动态规划, 二叉树
小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为 root 。
root
除了 root 之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果 两个直接相连的房子在同一天晚上被打劫 ,房屋将自动报警。
给定二叉树的 root 。返回 在不触动警报的情况下 ,小偷能够盗取的最高金额 。
示例 1:
输入: root = [3,2,3,null,3,null,1] 输出: 7 解释: 小偷一晚能够盗取的最高金额 3 + 3 + 1 = 7
示例 2:
输入: root = [3,4,5,1,3,null,1] 输出: 9 解释: 小偷一晚能够盗取的最高金额 4 + 5 = 9
提示:
Language: JavaScript
/** * 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) * } */ /** * @param {TreeNode} root * @return {number} */ var rob = function(root) { // 后序遍历函数 const postOrder = node => { if (!node) return [0, 0] const left = postOrder(node.left) const right = postOrder(node.right) // 不偷当前节点,左右子节点都可以偷或不偷,取最大值 const DoNot = Math.max(left[0], left[1]) + Math.max(right[0], right[1]) // 偷当前节点,左右子节点只能不偷 const Do = node.val + left[0] + right[0] // [不偷,偷] return [DoNot, Do] } const res = postOrder(root) // 返回最大值 return Math.max(...res) }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
337. 打家劫舍 III
Description
Difficulty: 中等
Related Topics: 树, 深度优先搜索, 动态规划, 二叉树
小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为
root
。除了
root
之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果 两个直接相连的房子在同一天晚上被打劫 ,房屋将自动报警。给定二叉树的
root
。返回 在不触动警报的情况下 ,小偷能够盗取的最高金额 。示例 1:
示例 2:
提示:
Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: