Tutorialspoint
Problem
Solution
Submissions

Binary Tree Maximum Path Sum

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the maximum path sum in a binary tree. A path is defined as any route along parent-child connections from some starting node to any ending node. The path must contain at least one node and does not need to go through the root.

Example 1
  • Input: root = [1,2,3]
  • Output: 6
  • Explanation:
    • Tree structure: 1 is root, 2 and 3 are its children.
    • Possible paths: [2], [1], [3], [2,1], [1,3], [2,1,3].
    • Path [2,1,3] gives maximum sum: 2 + 1 + 3 = 6.
    • Therefore, maximum path sum is 6.
Example 2
  • Input: root = [-10,9,20,null,null,15,7]
  • Output: 42
  • Explanation:
    • Tree has -10 as root, 9 and 20 as children of root, 15 and 7 as children of 20.
    • The optimal path is [15,20,7] which doesn't include the root.
    • Path sum: 15 + 20 + 7 = 42.
    • Therefore, 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 number of nodes
  • Space Complexity: O(h) where h is height of tree (recursion stack)
Binary TreeDeloitteSnowflake
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 post-order traversal to process children before parent nodes
  • For each node, calculate maximum path sum that ends at that node
  • Consider three cases: path through left child, path through right child, or path through both children
  • Keep track of global maximum path sum encountered during traversal
  • Return the maximum single-branch path sum to parent for further calculations
  • Handle negative path sums by choosing 0 instead (don't include negative branches)

Steps to solve by this approach:

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

 Step 2: Use post-order traversal to process children nodes before their parent.
 Step 3: For each node, recursively calculate maximum path sums from left and right subtrees.
 Step 4: Ignore negative path contributions by taking maximum of 0 and calculated sum.
 Step 5: Calculate the maximum path sum that passes through the current node (includes both children).
 Step 6: Update the global maximum if the current node's path sum is greater.
 Step 7: Return the maximum single-branch path sum to the parent for further calculations.

Submitted Code :