Task example: Path Sum

Follow child links from the root to a leaf. Return True if at least one complete path has values that add up to targetSum. A leaf has no children; stopping at an internal node does not count.

Example 1
Input
root = [5,4,8,1,2]
targetSum = 11
Output
True

The path 5 → 4 → 2 totals 11 and ends at a leaf.

Example 2
Input
root = [1,2]
targetSum = 1
Output
False

The root matches 1, but it is not a leaf. The only complete path totals 3.

LeetCode 112 ↗
01 / Recursive DFS

Recursive DFS: video explanation

root = [5,4,8,1,2]
targetSum = 11
output: True

Prefer reading? Follow the steps below.

  1. At each node, subtract its value from the amount still needed. An empty subtree returns False.
  2. At a leaf, return True only when the remaining amount is zero. A matching internal node is not enough.
  3. Try the left subtree, then the right. Stop as soon as either finds a matching root-to-leaf path.

Time complexity · O(n)

Each node is visited at most once. Finding a matching leaf can stop the search early.

Space complexity · O(h)

Recursive calls use O(h) space, where h is the tree height: O(log n) for a balanced tree and O(n) for a skewed tree.

PYTHONLive code trace
02 / Iterative DFS

Iterative DFS: video explanation

root = [5,4,8,1,2]
targetSum = 11
output: True

Prefer reading? Follow the steps below.

  1. Store a node and its running path total together on a stack. Start with the root and its value.
  2. Pop one pair. At a leaf, compare its total with targetSum and return True if they match.
  3. Push existing right and left children with their updated totals. If the stack empties without a match, return False.

Both approaches have the same worst-case bounds. Iterative DFS avoids Python's recursion limit. Negative values are allowed, so do not prune a path just because a partial total exceeds the target.

Time complexity · O(n)

Each node is visited at most once. Finding a matching leaf can stop the search early.

Space complexity · O(h)

The stack holds pending nodes along the DFS path: O(h) extra space, at most O(n).

PYTHONLive code trace

Path Sum · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.