Skip to content

  • Home
    • Featured Questions
    • Latest Updates
  • Subjects
    • Mathematics
    • Science
    • Computers
    • English
    • General Knowledge
    • History
  • Tips & Strategies
    • Test taking strategy
    • Stress Management
    • Time Management
  • Tools & Utilities
    • Generate Speech From Text
    • Change Your Voice
    • Generate Image From Text
    • Compress Your Images
  • Contact
    • Privacy Policy
    • Mission & Vision
  • Toggle search form

LeetCode Hard – Binary Tree Maximum Path Sum

Posted on February 10, 2024February 10, 2024 By allexamprep.com No Comments on LeetCode Hard – Binary Tree Maximum Path Sum

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.

Example 1:

Input: root = [1,2,3]

Output: 6

Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Example 2:

Input: root = [-10,9,20,null,null,15,7]

Output: 42

Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

Constraints:

  • The number of nodes in the tree is in the range [1, 3 * 104].
  • -1000 <= Node.val <= 1000

Java Solution

To solve this problem, you can use a recursive approach to traverse the binary tree and calculate the maximum path sum for each node. At each node, you need to consider the maximum sum that includes the current node (i.e., the node is part of the path), and the maximum sum that goes through the current node (i.e., the path goes from the left subtree to the current node to the right subtree).

Here’s the Java solution:

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) {
        this.val = val;
    }
}

public class BinaryTreeMaximumPathSum {
    private int maxPathSum = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        calculateMaxPathSum(root);
        return maxPathSum;
    }

    private int calculateMaxPathSum(TreeNode node) {
        if (node == null) {
            return 0;
        }

        // Calculate the maximum path sum for the left and right subtrees
        int leftMax = Math.max(0, calculateMaxPathSum(node.left));
        int rightMax = Math.max(0, calculateMaxPathSum(node.right));

        // Update the global maximum path sum considering the current node
        maxPathSum = Math.max(maxPathSum, leftMax + rightMax + node.val);

        // Return the maximum path sum that includes the current node (i.e., the node is part of the path)
        return Math.max(leftMax, rightMax) + node.val;
    }

    public static void main(String[] args) {
        BinaryTreeMaximumPathSum solution = new BinaryTreeMaximumPathSum();

        // Example 1
        TreeNode root1 = new TreeNode(1);
        root1.left = new TreeNode(2);
        root1.right = new TreeNode(3);
        System.out.println(solution.maxPathSum(root1));  // Output: 6

        // Example 2
        TreeNode root2 = new TreeNode(-10);
        root2.left = new TreeNode(9);
        root2.right = new TreeNode(20);
        root2.right.left = new TreeNode(15);
        root2.right.right = new TreeNode(7);
        System.out.println(solution.maxPathSum(root2));  // Output: 42
    }
}

This Java code defines a TreeNode class for the tree nodes and a BinaryTreeMaximumPathSum class with the maxPathSum method. The calculateMaxPathSum method is a recursive helper function to calculate the maximum path sum for each node. The maxPathSum variable is used to store the global maximum path sum. The provided test cases demonstrate its usage.

Python Solution

Here’s the equivalent Python solution for finding the maximum path sum in a binary tree:

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class BinaryTreeMaximumPathSum:
    def __init__(self):
        self.maxPathSum = float('-inf')

    def maxPathSum(self, root):
        self.calculateMaxPathSum(root)
        return self.maxPathSum

    def calculateMaxPathSum(self, node):
        if not node:
            return 0

        # Calculate the maximum path sum for the left and right subtrees
        left_max = max(0, self.calculateMaxPathSum(node.left))
        right_max = max(0, self.calculateMaxPathSum(node.right))

        # Update the global maximum path sum considering the current node
        self.maxPathSum = max(self.maxPathSum, left_max + right_max + node.val)

        # Return the maximum path sum that includes the current node (i.e., the node is part of the path)
        return max(left_max, right_max) + node.val

# Test cases
solution = BinaryTreeMaximumPathSum()

# Example 1
root1 = TreeNode(1)
root1.left = TreeNode(2)
root1.right = TreeNode(3)
print(solution.maxPathSum(root1))  # Output: 6

# Example 2
root2 = TreeNode(-10)
root2.left = TreeNode(9)
root2.right = TreeNode(20)
root2.right.left = TreeNode(15)
root2.right.right = TreeNode(7)
print(solution.maxPathSum(root2))  # Output: 42

This Python code uses a similar structure as the Java solution. The TreeNode class represents the tree nodes, and the BinaryTreeMaximumPathSum class contains the maxPathSum method. The calculateMaxPathSum method is a recursive helper function to calculate the maximum path sum for each node. The maxPathSum attribute is used to store the global maximum path sum. The provided test cases demonstrate its usage.

LEETCode Tags:LeetCode Hard

Post navigation

Previous Post: LeetCode Hard – Best Time to Buy and Sell Stock III
Next Post: LeetCode Hard – Word Ladder II

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Seminar Topic: “Adversarial Machine Learning: Challenges, Defense Mechanisms, and Real-World Implications”
  • Title: Exploring Explainable Artificial Intelligence (XAI) in Deep Learning
  • Project: Simple Weather App with OpenWeatherMap API
  • Project: Web Scraping Quotes with BeautifulSoup
  • Project: Automated Document Summarization with Gensim

Recent Comments

  1. Mystic Knightt on How to get generated id in spring batch template insert
  2. Sachin on How to get generated id in spring batch template insert

Archives

  • February 2024
  • January 2024

Categories

  • Biology
  • Blog
  • Computer QnA
  • LEETCode
  • Projects
  • Privacy Policy
  • Terms Of Service
  • Contact
  • About Us

Copyright © 2025 .

AllExamPrep