Skip to main content

14. Path Sum

easyAsked at CircleCI

Determine if a binary tree has a root-to-leaf path summing to a target, analogous to checking if a CI pipeline path meets a cost budget.

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 in [0, 5000]
  • Node values in [-1000, 1000]
  • targetSum in [-1000, 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 DFS

Recursively subtract node value from target and check if leaf with remainder 0 exists.

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:

2. Iterative DFS with stack

Push (node, remainingSum) pairs onto a stack, avoiding recursion overhead for deep trees.

Time
O(n)
Space
O(h)
function hasPathSum(root, target) {
  if (!root) return false;
  const stack = [[root, target]];
  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:

CircleCI-specific tips

CircleCI relates this to budget-constrained pipeline paths — be ready to extend the solution to return the actual path or count all valid paths.

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 CircleCI interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →