80. Path Sum
easyAsked at OlaDecide if any root-to-leaf path of a binary tree sums to a target.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
Constraints
Number of nodes is in [0, 5000]-1000 <= Node.val <= 1000
Examples
Example 1
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22trueExample 2
root = [1,2,3], targetSum = 5falseApproaches
1. Collect all paths
Enumerate every root-to-leaf path; check sums.
- Time
- O(n*h)
- Space
- O(n*h)
// list all paths then test sum; wastefulTradeoff:
2. DFS with remainder
Subtract node.val from target; at a leaf return whether remainder hits zero.
- Time
- O(n)
- Space
- O(h)
function hasPathSum(root, target) {
if (!root) return false;
if (!root.left && !root.right) return root.val === target;
return hasPathSum(root.left, target - root.val) || hasPathSum(root.right, target - root.val);
}Tradeoff:
Ola-specific tips
Ola interviewers like the subtract-down recursion; tie it to checking whether a chain of toll segments adds up to a target trip cost.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Path Sum and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →