Problem · Tree
Binary Tree Maximum Path Sum
Learn this problemProblem statement
Given the root of a non-empty binary tree whose nodes contain integers, return the maximum sum of a non-empty path.
A path is a sequence of distinct nodes where consecutive nodes share an edge. The path may start and end at any nodes and does not need to pass through the root. A node may appear at most once in the path.
Function
maxPathSum(root: TreeNode) → intExamples
Example 1
root = [1,2,3]return = 6The path 2 -> 1 -> 3 has sum 6.
Example 2
root = [-10,9,20,null,null,15,7]return = 42The best path is 15 -> 20 -> 7, whose sum is 42.
Example 3
root = [-3]return = -3A path must contain at least one node, so the single node is the answer.
Constraints
- The tree contains between
1and5000nodes. - Each node value is between
-1000and1000. - The tree height is at most
1000.