Path Sum III (prefix sum on a tree)
Problem Statement
You are given the root of a binary tree and a number targetSum.
Count the downward paths whose node values add up to targetSum. A path can start at any node and end at any node below it, but it must only go from parent to child. It does not have to start at the root or end at a leaf.
The root of a binary tree (it may be empty) and an integer targetSum. Node values can be negative.
The number of downward paths with sum targetSum.
The paths are 5 → 3, 5 → 2 → 1 and -3 → 11.
The paths are 5 → 4 → 11 → 2, 5 → 8 → 4 → 5 and 4 → 11 → 7.
- • 0 ≤ number of nodes ≤ 1000
- • −10^9 ≤ Node.val ≤ 10^9
- • −1000 ≤ targetSum ≤ 1000
- • Path sums can exceed the int range — use long long.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each node, DFS downward and count paths that hit the target
DFS with a map of path prefixes: ans += seen[cur − target], insert, recurse, undo
Any path has a top node. So for every node, walk down through its whole subtree, keeping a running sum, and count each time the sum equals the target. Then do the same for every other node.
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 Prefix Sum 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.