HARD NC#59 Blind #63 Trees
124. Binary Tree Maximum Path Sum
📖 Problem
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path.
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
- •In-place array updates
- •Sorted array traversal
- •Boundary condition checks
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply Two Pointers reasoning pattern
💡 Approach
- → For each node, calculate max gain from left and right subtrees
- → Negative gains are ignored (treated as 0)
- → Track maximum path sum seen so far (node + left + right)
- → Return max gain to parent (node + max(left, right))
- → Time: O(n), Space: O(h) where h is tree height
🧭 Prerequisites
🛠️ Hints & Pitfalls
Hints
- •For each node, calculate max gain from left and right subtrees
- •Negative gains are ignored (treated as 0)
- •Track maximum path sum seen so far (node + left + right)
Common Pitfalls
- •Return max gain to parent (node + max(left, right))
- •Time: O(n), Space: O(h) where h is tree height
🧪 Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
maxGain(node: TreeNode | null); Expected:
Computed from hidden reference Test Case 2
Not run Input:
maxGain(node.left); Expected:
Computed from hidden reference Test Case 3
Not run Input:
maxGain(node.right); Expected:
Computed from hidden reference 📝 Code Editor
📤 Output