Binary Tree Maximum Path Sum
1 approach, code in every language
Problem description
A path in a binary tree is any sequence of nodes in which each consecutive pair is connected by a parent-child edge. A node may appear in a path at most once, and the path is not required to pass through the root. The path sum is the total of the values of the nodes on that path.
Given the root of a binary tree, return the maximum possible path sum over all paths in the tree. Every tree has at least one node, so at least one path always exists.
Example 1
Input: root = [1,2,3]
Output: 6
The optimal path is 2 -> 1 -> 3 with a sum of 2 + 1 + 3 = 6.
Example 2
Input: root = [-10,9,20,null,null,15,7]
Output: 42
The optimal path is 15 -> 20 -> 7 with a sum of 15 + 20 + 7 = 42; the negative root is skipped.
Constraints
The number of nodes in the tree is in the range [1, 3 * 10^4].-1000 <= Node.val <= 1000
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Best Chamber Run is our own problem on the technique behind Binary Tree Maximum Path Sum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free