13. Path Sum
easyAsked at Electronic ArtsDetermine if a binary tree has a root-to-leaf path that sums to a target value, a pattern used in EA game scene-graph traversals.
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. A leaf is a node with no children.
Constraints
Number of nodes in the tree is in the range [0, 5000]-1000 <= Node.val <= 1000-1000 <= targetSum <= 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. Brute force DFS
Recursively explore every root-to-leaf path and check if any sums to target.
- Time
- O(n)
- Space
- O(h)
function hasPathSum(root, targetSum) {
if (!root) return false;
if (!root.left && !root.right) return root.val === targetSum;
return hasPathSum(root.left, targetSum - root.val) ||
hasPathSum(root.right, targetSum - root.val);
}Tradeoff:
2. Iterative DFS with stack
Use an explicit stack storing [node, remainingSum] pairs to avoid recursion overhead. This mirrors how EA's scene-graph walkers handle deep tree traversals in engine code.
- Time
- O(n)
- Space
- O(h)
function hasPathSum(root, targetSum) {
if (!root) return false;
const stack = [[root, targetSum]];
while (stack.length) {
const [node, rem] = stack.pop();
if (!node.left && !node.right && rem === node.val) return true;
if (node.right) stack.push([node.right, rem - node.val]);
if (node.left) stack.push([node.left, rem - node.val]);
}
return false;
}Tradeoff:
Electronic Arts-specific tips
EA interviews cover game development data structures, pathfinding (A*, BFS on grids), spatial algorithms, and simulation problems. Grid/matrix manipulation and BFS on 2D arrays are very common.
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 Electronic Arts interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →