Skip to content

Path Sum

Decide whether some root-to-leaf path adds up to the target, subtracting each value on the way down.

EasyTree DFS and BST
Solve on LeetCode

The problem

You get the root of a binary tree and an integer targetSum. Return true if some path from the root down to a leaf has values that add up to targetSum, and false otherwise. A leaf is a node with no children, and an empty tree has no paths at all.

Input root = [3, 9, 4, null, null, 6, 1], targetSum = 13

Output true

The path 3, 4, 6 ends at a leaf and 3 + 4 + 6 = 13.

Input root = [3, 9, 4, null, null, 6, 1], targetSum = 7

Output false

3 + 4 = 7, but 4 is not a leaf, so that path does not count. The full paths add up to 12, 13 and 8.

How to spot the pattern

  • The paths you care about start at the root and end at a leaf.
  • What a subtree still has to add up to depends only on what the path above it has used.

The idea

Walking down from the root, each node uses up part of the target. So when you move to a child, ask a smaller question: does this subtree have a root-to-leaf path that adds up to targetSum - node.val? At a leaf the question becomes simple: is what is left exactly 0?

Brute force: Write out every root-to-leaf path as a list and add each one up, which costs O(n * h) time because the top part of each path is copied again.

Step by step

  1. 1If the node is null, return false.
  2. 2Subtract the node's value from the target to get what is still needed.
  3. 3If the node is a leaf, return whether what is still needed is 0.
  4. 4Otherwise return true if the left or the right subtree has a path for the smaller target.

See the pattern move

The tree dfs and bst pattern on a small example. Step through it, or press play.

Code

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if root is None:
            return False
        remaining = targetSum - root.val
        if root.left is None and root.right is None:
            return remaining == 0  # a leaf: the path ends here
        return self.hasPathSum(root.left, remaining) or self.hasPathSum(root.right, remaining)

Complexity

Time

O(n)

Space

O(h)

Each node is visited at most once and the search stops as soon as one path works; the stack holds one call per level.

Watch out for

  • Stopping at a node in the middle whose running total hits the target: the path must end at a leaf.
  • Returning true for an empty tree when targetSum is 0; an empty tree has no root-to-leaf path.
  • Giving up once the running sum passes the target: values can be negative, so a later node can bring it back down.

Follow-up questions

What if you must return every root-to-leaf path that works?

Keep the current path in a list, add each node on the way down and remove it on the way back up, and save a copy at every matching leaf. That is Path Sum II.

What if a path may start and end anywhere, as long as it goes downward?

Keep a map of prefix sums along the current root-to-node path and count the earlier prefixes equal to current - target, as in Subarray Sum Equals K. That is Path Sum III.

In Hinglish

Neeche jaate hue target mein se har node ki value ghatate jao. Leaf par bacha hua 0 ho toh path mil gaya; beech ke node par rukna allowed nahi.

Related problems