Accenture · Question 48 · Trees
Path Sum
Problem
Given a binary tree and a sum, determine if the tree has a root - to - leaf path such that adding up all values equals the sum.
Approach
DFS through the tree subtracting current node value from sum, check leaf nodes.
Time O(n)Space O(h)
How it works
- 1Subtract node values down the path.
- 2Only a matching leaf completes it.
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