This is a classic problem often referred to as the "Binary Tree Maximum Path Sum." The key challenge here is that the path can start and end anywhere in the tree, not necessarily including the root and not necessarily at a leaf.
Understanding the Problem
- Path: sequence of nodes with edges connecting adjacent nodes.
- Nodes in the path are unique (cannot reuse the same node).
- The path doesn't need to include the root.
- We want to find the maximum possible sum of any such path in the tree.
Approach
To solve this, we use a recursive DFS approach that:
- At each node, computes the maximum path sum starting from its left child and right child.
- The path that goes through the current node could be:
- Only the current node.
- Current node + max path sum from left child.
- Current node + max path sum from right child.
- Current node + max path sum from left child + max path sum from right child.
Why consider the 4th case? Because the path could "turn" at the current node and use both sides.
However, when returning to the parent, we can only choose one side (or none) because paths cannot branch if we are continuing upwards (paths can't reuse nodes).
The main idea:
- Recursively compute the "max gain" from left and right children.
- Calculate the "price" of the new path that goes through this node (
node.val + left_gain + right_gain).
- Update the global max if price is bigger.
- Return
node.val + max(left_gain, right_gain, 0) to be used as gain for the parent.
Step-by-step Example:
Given the example tree:
1
/ \
2 3
- Left max gain for node 2 = 2
- Right max gain for node 3 = 3
- For node 1:
- Price of new path: 1 + 2 (left) + 3 (right) = 6
- Update global max to 6
- Return gain to parent: 1 + max(2,3) = 4
Since 1 is the root, the result is 6.
Code Implementation in Python:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.max_sum = float('-inf')
def max_gain(node):
if not node:
return 0
# max sum on the left and right subtrees of node
left_gain = max(max_gain(node.left), 0) # only count if positive
right_gain = max(max_gain(node.right), 0)
# price of the path going through this node (including both children)
price_newpath = node.val + left_gain + right_gain
# update max_sum if it's better to start a new path
self.max_sum = max(self.max_sum, price_newpath)
# for recursion: return the max gain if continue the same path
return node.val + max(left_gain, right_gain)
max_gain(root)
return self.max_sum
Explanation:
max_gain(node) returns max sum from the current node continuing downwards (no splits).
- While returning, we update the global max sum considering both children and self.
- Finally, return the max path sum stored in
self.max_sum.
Complexity:
- Time complexity: O(N), where N is the number of nodes (we visit each once).
- Space complexity: O(H), where H is the height of the tree (call stack of recursion).
Feel free to ask if you want me to help with other variants or optimizations!