Problems
Binary Tree Maximum Path Sum
Hard·Tagstreedfsrecursiondynamic-programming
Problem Statement
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the `root` of a binary tree, return the maximum path sum of any non-empty path.
Note: Assume a standard `TreeNode` class is already provided in the execution environment, containing `val`, `left`, and `right` properties.
Examples
Example 1
Input
root: [1, 2, 3]Tree
Output
"6"Why
The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
Example 2
Input
root: [-10, 9, 20, null, null, 15, 7]Tree
Output
"42"Why
The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
Example 3
Input
root: [-3]Tree
Output
"-3"Why
The tree only has one node, so the maximum path sum is the value of that node.
Constraints
- •The number of nodes in the tree is in the range [1, 3 * 10^4].
- •-1000 <= Node.val <= 1000
Hints
Stuck? Reveal a nudge toward the right pattern, one step at a time.
Hint 1
A path can look like an inverted 'V'. It goes up a left branch, hits a pivot node, and goes down the right branch. The maximum path might not even include the root!
Hint 2
Just like finding the Diameter of a Binary Tree, you can use a global/reference variable `maxSum` to keep track of the maximum 'inverted V' path found so far.
Hint 3
A recursive `dfs(node)` function should return the maximum path sum of a *straight* line going downwards from that node. Why? Because a parent node can only connect to one of its children's branches to form a valid path.
Hint 4
If a child's maximum straight path sum is negative, it will only drag your total sum down. You should ignore it completely by taking `max(dfs(node.left), 0)`!