var rob = function(root) {
function dfs(node) {
if (!node) return [0, 0]; // [不偷当前节点的最大金额, 偷当前节点的最大金额]
const left = dfs(node.left);
const right = dfs(node.right);
// 如果不偷当前节点,那么可以偷或不偷左右子节点
const notRobCurrent = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
// 如果偷当前节点,那么不能偷左右子节点
const robCurrent = node.val + left[0] + right[0];
return [notRobCurrent, robCurrent];
}
const result = dfs(root);
return Math.max(result[0], result[1]);
};
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
function buildTree(preorder) {
if (preorder.length === 0) return null;
let root = new TreeNode(preorder[0]);
let queue = [root];
let i = 1;
while (i < preorder.length) {
let currentNode = queue.shift();
if (preorder[i] !== null) {
currentNode.left = new TreeNode(preorder[i]);
queue.push(currentNode.left);
}
i++;
if (i < preorder.length && preorder[i] !== null) {
currentNode.right = new TreeNode(preorder[i]);
queue.push(currentNode.right);
}
i++;
}
return root;
}
var rob = function (root) {
if (!root) return 0;
let evenSum = 0,
oddSum = 0;
function dfs(node, higt) {
if (!node) return [0, 0]; //返回两个值:[偷当前节点的最大金额, 不偷当前节点的最大金额]
// 递归计算左子树和右子树的最大金额
let left = dfs(node.left, higt + 1);
let right = dfs(node.right, higt + 1);
// 如果偷当前节点,则不能偷其左右子节点
const robThisNode = node.val + left[1] + right[1];
// 如果不偷当前节点,则可以选择偷或不偷其左右子节点
const notRobThisNode =
Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
if (higt % 2 === 0) {
evenSum = Math.max(robThisNode, notRobThisNode);
} else {
oddSum = Math.max(robThisNode, notRobThisNode);
}
// 返回当前节点偷和不偷的最大金额
return [robThisNode, notRobThisNode];
}
dfs(root, 0);
return Math.max(evenSum, oddSum);
};
// 构建二叉树
let preorder = [4, 1, null, 2, null, 3];
let root = buildTree(preorder);
console.log(rob(root));
'
标签:node,preorder,right,root,337,打家劫舍,III,节点,left From: https://www.cnblogs.com/KooTeam/p/18675894