Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Binary Tree Maximum Path Sum in Python
The maximum path sum problem asks us to find the path in a binary tree with the largest sum of node values. A path can start and end at any nodes and must follow parent-child connections. The path doesn't need to pass through the root.
Algorithm
The solution uses a recursive approach with the following logic:
For each node, calculate the maximum sum path that includes this node
Consider paths going through left subtree, right subtree, or both
Use negative contributions as 0 (ignore negative paths)
Track the global maximum across all possible paths
Implementation
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(temp, data):
queue = []
queue.append(temp)
while len(queue):
temp = queue.pop(0)
if not temp.left:
if data is not None:
temp.left = TreeNode(data)
else:
temp.left = TreeNode(0)
break
else:
queue.append(temp.left)
if not temp.right:
if data is not None:
temp.right = TreeNode(data)
else:
temp.right = TreeNode(0)
break
else:
queue.append(temp.right)
def make_tree(elements):
if not elements:
return None
tree = TreeNode(elements[0])
for element in elements[1:]:
insert(tree, element)
return tree
class Solution:
def maxPathSum(self, root):
self.max_sum = float('-inf')
self.solve(root)
return self.max_sum
def solve(self, node):
if not node or node.data == 0:
return 0
# Get maximum sum from left and right subtrees
left = max(0, self.solve(node.left))
right = max(0, self.solve(node.right))
# Update global maximum considering path through current node
current_max = left + right + node.data
self.max_sum = max(self.max_sum, current_max)
# Return maximum sum including current node for parent calls
return node.data + max(left, right)
# Example usage
solution = Solution()
root = make_tree([-10, 9, 10, None, None, 15, 7])
result = solution.maxPathSum(root)
print(f"Maximum path sum: {result}")
Maximum path sum: 32
How It Works
The algorithm works by:
Recursive exploration: Visit each node and calculate the maximum path sum ending at that node
Path consideration: For each node, consider three possibilities − path through left subtree only, right subtree only, or both subtrees
Negative handling: Use
max(0, subtree_sum)to ignore negative contributionsGlobal tracking: Maintain a global maximum that gets updated whenever a better path is found
Time and Space Complexity
Time Complexity: O(n) where n is the number of nodes, as we visit each node exactly once.
Space Complexity: O(h) where h is the height of the tree due to recursion stack.
Conclusion
The maximum path sum problem is solved using recursive traversal with dynamic programming principles. The key insight is tracking both local optimal paths and global maximum simultaneously during tree traversal.
