Tutorialspoint
Problem
Solution
Submissions

Maximum Path Sum in Binary Tree

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 8

Write a C# function 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 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: root = [1, 2, 3]

    Maximum Path Sum With root node 1
  • Output: 6
  • Explanation:
    • The maximum path sum is the path [2, 1, 3], with sum = 6.
Example 2
  • Input: root = [-10, 9, 20, null, null, 15, 7]

    Maximum Path Sum With root node -10

  • Output: 42
  • Explanation:
    • The maximum path sum is the path [15, 20, 7], with sum = 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)
  • Space Complexity: O(h), where h is the height of the tree

RecursionTreeHCL TechnologiesPhillips
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 recursion to traverse the tree
  • For each node, compute the maximum path sum that includes the node as the highest point
  • Update the global maximum path sum during traversal
  • Handle negative values appropriately
  • Consider both including and excluding the current node in the path

Steps to solve by this approach:

Step 1: Define a recursive function that calculates the maximum path sum for each subtree.
Step 2: For each node, calculate the maximum path sum from the left and right subtrees.
Step 3: If a subtree's path sum is negative, we discard it by taking max with 0.
Step 4: Update the global maximum by considering the path that includes the current node as the highest point (node.val + leftMax + rightMax).
Step 5: Return the maximum path sum that can be extended to the parent node (node.val + max(leftMax, rightMax)).


Submitted Code :