
Problem
Solution
Submissions
Binary Tree Maximum Path Sum
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a JavaScript program to find the maximum path sum in a binary tree. A path is defined as any sequence of nodes 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 node values along the path.
Example 1
- Input: root = [1,2,3]
- Output: 6
- Explanation:
- The tree has nodes with values 1, 2, and 3.
- The optimal path is 2 -> 1 -> 3.
- The sum of this path is 2 + 1 + 3 = 6.
- Therefore, the maximum path sum is 6.
- The tree has nodes with values 1, 2, and 3.
Example 2
- Input: root = [-10,9,20,null,null,15,7]
- Output: 42
- Explanation:
- The tree has nodes with values -10, 9, 20, 15, and 7.
- The optimal path is 15 -> 20 -> 7.
- The sum of this path is 15 + 20 + 7 = 42.
- This path doesn't include the root node -10 as it would decrease the sum.
- Therefore, the maximum path sum is 42.
- The tree has nodes with values -10, 9, 20, 15, and 7.
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
- 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 depth-first search (DFS) to traverse the tree recursively
- For each node, calculate the maximum path sum that ends at that node
- At each node, consider four possibilities: node only, node + left subtree, node + right subtree, or node + both subtrees
- Keep track of the global maximum path sum found so far
- Return the maximum path sum that can be extended upward from each node
- Handle negative values by choosing not to include negative subtree paths