
分析
- 路径每到一个节点,有 3 种选择:1. 停在当前节点。2. 走到左子节点。3. 走到右子节点;
- 一个子树内部的最大路径和 = 左子树提供的最大路径和 + 根节点值 + 右子树提供的最大路径和;
- 如果某个子树 dfs 结果为负,走入它,收益不增反减,该子树就没用,需杜绝走入,返回 0;
- 一条从父节点延伸下来的路径,不能走入左子树又掉头走右子树,不能两头收益;
function maxPathSum(root) {
let max = Number.MIN_SAFE_INTEGER;
const dfs = (node) => {
if (!node) return 0;
const left = dfs(node.left);
const right = dfs(node.right);
max = Math.max(max, node.val + left + right);
const outputMax = node.val + Math.max(0, left, right);
return outputMax > 0 ? outputMax : 0;
};
dfs(root);
return max;
}