Path Sum II
Problem Statement
You are given the root of a binary tree and a number targetSum.
Find every root-to-leaf path whose values add up to targetSum. A root-to-leaf path starts at the root and ends at a leaf (a node with no children). Return each matching path as a list of its node values, not as node references.
The root of a binary tree (it can be empty) and an integer targetSum.
A list of every matching path. Each path is a list of values from the root down to a leaf.
5 + 4 + 11 + 2 = 22 and 5 + 8 + 4 + 5 = 22. The path 4 → 11 → 7 also adds to 22, but it does not start at the root, so it does not count.
The two paths add to 3 and 4. Neither is 5.
The only path, 1 → 2, adds to 3.
- • The tree has between 0 and 5000 nodes.
- • −1000 ≤ Node.val ≤ 1000
- • −1000 ≤ targetSum ≤ 1000
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Pass the path by value, so every call copies the whole path built so far
Push and pop one vector as we walk; copy it into the answers at matching leaves
Give each call its own vector of values. A call adds its node to the vector it was given, and passes a full copy of that vector to each child. When a leaf matches, its vector is an 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.