124. 二叉树中的最大路径和

路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和 。

链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let maxG = Number.NEGATIVE_INFINITY

function maxPathSum(root: TreeNode | null): number {
if (root === null) return 0
maxG = Number.NEGATIVE_INFINITY
traverse(root)
return maxG
};

function traverse(root: TreeNode): number {
if (root === null) return 0
const leftG = Math.max(traverse(root.left), 0)
const rightG = Math.max(traverse(root.right), 0)
const max = root.val + leftG + rightG
maxG = Math.max(max, maxG)
return root.val + Math.max(leftG, rightG)
}