Capgemini · Question 54 · Trees
Path Sum
Problem
You are given root and target sum. Check if there's root-to-leaf path summing to target.
Approach
Subtract node values along the way; a leaf must match the remainder exactly.
Time O(n)Space O(h)
How it works
- 1Carry the remaining sum downward.
- 2Only a matching leaf completes the path.
Sample input / output
Input: root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], targetSum = 22 Output: true
Constraints
0 <= nodes <= 5000.
Solution — read it, then walk it
Time O(n)Space O(h)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/21
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits