124. Binary Tree Maximum Path Sum
Asked at 24Amazon60Meta52Microsoft49Bloomberg49Google47Apple22TikTok56Goldman Sachs36Baidu100DoorDash89Wix87Nutanix71Adobe69Citadel64Datadog53Salesforce52Yandex49Snap45Flipkart43PayPal42Oracle41Uber35Infosys30tcs27
Problem
A path is any sequence of nodes connected by parent-child edges, using each node at most once; it doesn't need to pass through the root and may bend at one node. Return the largest sum of node values over all non-empty paths. Values can be negative.
Example: [-10,9,20,null,null,15,7] → 42 (15 → 20 → 7)
Each node returns the best downward path gain (max(0, left, right) + val, negatives dropped). The best path through the node uses both sides: val + max(0,L) + max(0,R) → update global answer.
-10
/ \
9 20 through 20: 15 + 20 + 7 = 42 (answer)
/ \ returns up: 20 + 15 = 35
15 7
Complexity: O(n).
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
best = float("-inf")
def gain(node):
nonlocal best
if not node:
return 0
l, r = max(gain(node.left), 0), max(gain(node.right), 0)
best = max(best, node.val + l + r)
return node.val + max(l, r)
gain(root)
return best
assert Solution().maxPathSum(make_tree([1, 2, 3])) == 6
assert Solution().maxPathSum(make_tree([-10, 9, 20, None, None, 15, 7])) == 42
assert Solution().maxPathSum(make_tree([-3])) == -3
class Solution {
private int best = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
gain(root);
return best;
}
private int gain(TreeNode n) {
if (n == null) return 0;
int l = Math.max(gain(n.left), 0), r = Math.max(gain(n.right), 0);
best = Math.max(best, n.val + l + r);
return n.val + Math.max(l, r);
}
}
func maxPathSum(root *TreeNode) int {
best := math.MinInt
var gain func(*TreeNode) int // best downward path starting at node
gain = func(node *TreeNode) int {
if node == nil {
return 0
}
l, r := max(gain(node.Left), 0), max(gain(node.Right), 0)
best = max(best, node.Val+l+r)
return node.Val + max(l, r)
}
gain(root)
return best
}