Skip to problem
←

Path Sum

Easy 0 attempts

Given a binary tree root and an integer targetSum, return true if at least one path from the root to a leaf has node values summing to targetSum. Otherwise, return false.

A leaf has no left or right child. Follow parent-to-child links and include both the root and leaf values. A path cannot stop at an internal node or start below the root. Values may be negative or zero.

An empty tree has no root-to-leaf path, so return false even when targetSum = 0. A single-node tree qualifies exactly when that node's value equals the target.

In the first example, the path 5 → 4 → 11 → 2 ends at a leaf and sums to 22. For root = [1, 2] and targetSum = 1, return false: the root alone reaches the target but is not a leaf.

Examples use level-order arrays with null for missing children. Your function receives nodes with val, left, and right properties.

Function contract

Implement hasPathSum(root, targetSum). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return true if a root-to-leaf path has the target sum; otherwise return false.

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
Constraints
  • 0 <= number of nodes <= 5000
  • -1000 <= Node.val, targetSum <= 1000

Iterative Depth-First Search

Keep a stack of [node, sumSoFar] pairs. Start with the root and its value. When visiting a leaf, compare the accumulated sum with the target. For each child, add its value and push the resulting state.

Only leaves can complete a path. Do not stop early because a partial sum exceeds the target: negative values later in the path can reduce it. If every path is exhausted without a matching leaf, return false.

An explicit stack avoids recursive call-stack limits on a long, one-sided tree.

javascript
function hasPathSum(root, targetSum) {
  if (!root) return false;
  const stack = [[root, root.val]];
  while (stack.length) {
    const [node, sum] = stack.pop();
    if (!node.left && !node.right && sum === targetSum) return true;
    if (node.right) stack.push([node.right, sum + node.right.val]);
    if (node.left) stack.push([node.left, sum + node.left.val]);
  }
  return false;
}

Time: O(n) | Space: O(h), where n is the number of nodes and h is tree height. The depth-first stack stores pending branches along the current path.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript