Skip to main content

14. Path Sum

easyAsked at Indeed

Check whether a root-to-leaf path in a binary tree sums to a target — a building block for Indeed's skill-weight aggregation in job-fit scoring.

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 node values along the path equals targetSum.

Constraints

  • 0 <= number of nodes <= 5000
  • -1000 <= Node.val, targetSum <= 1000

Examples

Example 1

Input
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output
true

Example 2

Input
root = [1,2,3], targetSum = 5
Output
false

Approaches

1. Brute force

Enumerate all root-to-leaf paths by DFS and compare each sum to target.

Time
O(n)
Space
O(n)
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:

2. Iterative DFS with stack

Push (node, remainingSum) pairs onto a stack to avoid recursion overhead and enable early exit.

Time
O(n)
Space
O(n)
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:

Indeed-specific tips

Indeed uses path-sum variants to test that candidates understand leaf detection — always verify both children are null before claiming a leaf node.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Path Sum and other Indeed interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →