
Problem
Solution
Submissions
Binary Tree Maximum Path Sum
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to find the maximum path sum in a binary tree. A path is defined as any node sequence from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. The path sum is the sum of the values of the nodes in the path.
Example 1
- Input:
- Output: 6
- Explanation: The maximum path sum is 6, from the path [2,1,3] where 2 + 1 + 3 = 6.
Example 2
- Input:
- Output: 42
- Explanation: The maximum path sum is 42, from the path [20,15,7] where 20 + 15 + 7 = 42.
Constraints
- The number of nodes in the tree is in the range [1, 3 * 10^4]
- -1000 <= Node.val <= 1000
- Time Complexity: O(n), where n is the number of nodes in the tree
- Space Complexity: O(h), where h is the height of the tree
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a recursive approach to solve this problem
- For each node, calculate the maximum path sum that can be achieved by including that node
- Keep track of two values for each node: the maximum path sum that passes through the node, and the maximum path sum that can be extended to the node's parent
- A path can go through a node's left child, the node itself, and its right child
- However, a path that can be extended to a parent can only include one child (either left or right, whichever gives the maximum sum)
- Use a global variable to keep track of the overall maximum path sum
- Handle negative values carefully, as it may be better to exclude a negative value subtree