Tutorialspoint
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.
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.
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
AlgorithmsBinary TreeKPMGD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize a global variable to track the maximum path sum found so far.
 Step 2: Create a recursive DFS function that calculates the maximum path sum ending at each node.
 Step 3: For each node, recursively calculate the maximum path sum from left and right subtrees.
 Step 4: Use Math.max(0, subtreeSum) to ignore negative subtree contributions.
 Step 5: Calculate the maximum path sum that passes through the current node (node + left + right).
 Step 6: Update the global maximum with the current node's maximum path sum.
 Step 7: Return the maximum path sum that can be extended upward (node + max(left, right)).

Submitted Code :