Program to find the largest sum of the path between two nodes in a binary tree in Python

In a binary tree, we often need to find the maximum sum path between any two nodes. This path doesn't have to go through the root and can be between any two nodes in the tree.

Given a binary tree like this:

13 12 14 16 22 4 7

The maximum sum path is 12 ? 13 ? 14 ? 16 ? 7 with a sum of 62.

Algorithm

We use a recursive approach with helper function:

  • For each node, calculate the maximum path sum ending at that node

  • Consider three cases: left subtree path, right subtree path, or path through current node

  • Track the global maximum across all nodes

Solution

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

class Solution:
    def solve(self, root):
        if root is None:
            return 0
        
        self.res = float("-inf")
        self.utils(root)
        return self.res
    
    def utils(self, root):
        if root is None:
            return 0
        
        # Get maximum path sum from left and right subtrees
        l = self.utils(root.left)
        r = self.utils(root.right)
        
        # Maximum path ending at current node (going down)
        max_single = max(max(l, r) + root.val, root.val)
        
        # Maximum path through current node (left + root + right)
        max_top = max(max_single, l + r + root.val)
        
        # Update global maximum
        self.res = max(self.res, max_top)
        
        # Return maximum path ending at current node
        return max_single

# Create the binary tree
ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)

print("Maximum path sum:", ob.solve(root))
Maximum path sum: 62

How It Works

The algorithm works by:

  1. max_single: Maximum sum path ending at current node (either through left, right, or just current node)

  2. max_top: Maximum sum considering path through current node (left + root + right)

  3. Global tracking: Keep updating the global maximum as we traverse

For each node, we return max_single because a path can only go through a node once when viewed from its parent.

Conclusion

This solution uses recursion to find the maximum path sum in O(n) time complexity. The key insight is tracking both the maximum path ending at each node and the global maximum across all possible paths.

Updated on: 2026-03-25T11:15:41+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements