Tutorialspoint
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:

    Binary Tree Maximum Path Sum with Root Node 1

  • Output: 6
  • Explanation: The maximum path sum is 6, from the path [2,1,3] where 2 + 1 + 3 = 6.
Example 2
  • Input:

    Binary Tree Maximum Path Sum eith Root Node -10

  • 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
RecursionBinary TreeTech MahindraKPMG
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 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

Steps to solve by this approach:

 Step 1: Create a global variable to track the maximum path sum found so far.

 Step 2: Implement a recursive helper function that computes the maximum contribution a node and its subtrees can add to the path sum.
 Step 3: For each node, calculate the maximum gain from its left subtree, ignoring negative contributions.
 Step 4: Calculate the maximum gain from its right subtree, also ignoring negative contributions.
 Step 5: Calculate the "price of a new path" starting at this node: node's value + left gain + right gain.
 Step 6: Update the global maximum sum if this new path has a greater sum.
 Step 7: Return the maximum gain this node can contribute to its parent: node's value + maximum of the left or right gain.

Submitted Code :