Binary Tree Maximum Path Sum
Problem Statement
You are given the root of a binary tree. A path is a sequence of nodes where each pair of neighbours is joined by an edge. Each node can appear in a path at most once.
A path does not have to start or end at the root, and it does not have to go through the root. Its path sum is the total of the node values on it. Node values can be negative.
Return the largest path sum over all paths. A path must contain at least one node.
The root of a binary tree. It has between 1 and 3 × 10^4 nodes. Values can be negative.
The largest path sum of any non-empty path.
The best path is 2 → 1 → 3, with sum 2 + 1 + 3 = 6. It goes through the root.
The best path is 15 → 20 → 7, with sum 42. It does not include the root, which has value −10.
The best path is still 15 → 20 → 7. It cannot also continue up to 1, because a path that goes through 20 on both sides cannot go up to 20's parent.
- • The number of nodes is in the range [1, 3 × 10^4].
- • −1000 ≤ Node.val ≤ 1000
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Treat each node as the top of the path, and search each of its sides from scratch
One post-order pass: each node returns its best one-side gain and records the best path that bends there
Every path has a top node where it turns. For each node, find the best downward sum on its left side and on its right side, using a separate search for each side. Add the node's value and both sides (a side with a negative sum is dropped). The largest total over all nodes is the answer.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.