Accenture · Question 53 · Trees
Path Sum III
Problem
Find the number of paths that sum to a given value in a binary tree. Paths do not need to start at root or end at leaf but must go downwards.
Approach
DFS with prefix sums stored in a hashmap to count paths efficiently.
Time O(n)Space O(n)
How it works
- 1Track running sums from the root.
- 2curr - target seen before means paths ending here hit it.
Sample input / output
Input: root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], targetSum = 8 Output: 3
Constraints
0 <= nodes <= 1000; -10^9 <= Node.val <= 10^9.
Solution — read it, then walk it
Time O(n)Space O(n)Loops 1Branches 2Returns 3source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/35
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