Skip to content
Problem 112 · LeetCode 112(opens in a new tab)

Path Sum

EasyRecursion

A binary tree starts at root, and you also get a whole number targetSum. A root-to-leaf path starts at the root and walks down, one child at a time, until it reaches a leaf: a node with no children at all.

Return true if some root-to-leaf path has values that add up to exactly targetSum, and false otherwise. An empty tree has no paths.

Example 1

Input:  root = [3, 9, -2, 1, null, 6, 4], targetSum = 7
Output: true
Why:    3 + (−2) + 6 = 7, and 6 is a leaf
2 more examples and the constraints

Example 2

Input:  root = [2, 5, 6], targetSum = 2
Output: false
Why:    the root is 2 but not a leaf; the paths add to 7 and 8

Example 3

Input:  root = [], targetSum = 0
Output: false
Why:    an empty tree has no path at all

Constraints

  • The tree has between 0 and 5,000 nodes
  • −1,000 ≤ each node value ≤ 1,000
  • −1,000 ≤ targetSum ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. BFS with running sumsO(n)
  2. Recursive DFS, subtract as you goO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a tree of 5,000 nodesVerdict
BFS with running sumsO(n)
Passes; holds a whole level
Recursive DFS, subtract as you goO(n)
Best; shortest code

n = number of nodes, w = widest level, h = height. Both stop at the first matching leaf.

Edge cases to test

  • Empty tree. There is no path, so even a target of 0 gives false.
  • The target is reached at an inner node. [2, 5, 6] with target 2: the root is not a leaf, so it does not count.
  • One child only. [1, null, 2] has one leaf, 2. The empty left slot is not a leaf and must not count as a path.
  • Negative values. A sum can go past the target and come back, so you cannot stop early when the running sum gets too big.

Common mistakes

  • Returning true when the remaining target hits 0 at a node that still has children.
  • Treating an empty child as a leaf, so [1, null, 2] with target 1 wrongly passes.
  • Pruning when the running sum exceeds the target, which breaks with negative values.

How to talk through it

  1. 1Clarify. Must the path end at a leaf? Can values be negative? What should an empty tree return?
  2. 2Shrink the problem. A path from the root works if a path from a child adds up to the target minus the root.
  3. 3Name the base cases. An empty node is false; a leaf is true when the rest is 0.
  4. 4Give the cost. O(n) time; O(h) stack, which is O(n) for a chain. Mention BFS with sums if recursion depth is a worry.
  5. 5Test out loud. Run the empty tree, a root that equals the target but has children, and a one-child node.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?