Binary Tree Maximum Path Sum is a classic "Hard" coding problem. 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 does not need to go through the root. Your task is to find the maximum possible sum of values along such a path. Since node values can be negative, this is much trickier than a simple tree traversal.
This is a favorite for top-tier companies like Meta, Amazon, and Google. It tests your mastery of recursion and your ability to handle "negative gain." It forces you to distinguish between two different things: the maximum path that can be extended to a parent, and the maximum path that exists within a subtree (which might not include the parent).
This problem uses the Post-order Traversal (DFS) combined with Dynamic Programming on trees. At each node, you calculate the "maximum contribution" it can offer to its parent. This contribution is node.val + max(0, left_gain, right_gain). Simultaneously, you update a global maximum by considering a path that "turns" at the current node: node.val + left_gain + right_gain.
Consider this tree:
-10
/
9 20
/
15 7
The biggest mistake is not handling negative values correctly. If a subtree has a negative maximum gain, it’s better to ignore it (treat it as 0) rather than adding it to the current path. Another mistake is trying to return the "split" path sum (left + root + right) to the parent, which is illegal as a path cannot branch into two children.
This problem is the "ultimate" tree recursion test. If you can explain why you return max(left, right) + node.val but update the global max with left + right + node.val, you've demonstrated a deep understanding of tree-based algorithms.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Binary Tree Cameras | Hard | Solve | |
| Minimum Flips in Binary Tree to Get Result | Hard | Solve | |
| House Robber III | Medium | Solve | |
| Longest ZigZag Path in a Binary Tree | Medium | Solve | |
| Maximum Sum BST in Binary Tree | Hard | Solve |