KatInterview

Path Sum Validation in Binary Trees

Trees & GraphsModel answer
EasyModel answerTrees & Graphsbinary-treedepth-first-searchtree-traversal

Last updated

Determine whether any root-to-leaf path in a binary tree sums to a given target value.

Problem

You are given a binary tree and an integer target_sum. Your task is to determine whether there exists any complete path from the root to a leaf node where the sum of all node values along that path equals target_sum.

Return True if such a path exists, otherwise return False.

Definitions

  • A leaf node has no children (both left and right are None)
  • A root-to-leaf path is a sequence of nodes starting from the root and ending at a leaf
  • An empty tree (where root is None) contains no paths

Function Signature

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def has_path_sum(root: TreeNode | None, target_sum: int) -> bool:
    pass

Input Constraints

  • Number of nodes: 0 to 5,000
  • Node values: -1,000 to 1,000
  • Target sum: -100,000 to 100,000

Examples

Example 1:

Tree:
        5
       / \
      4   8
     /   / \
    11  13  4
   / \       \
  7   2       1

target_sum = 22
Output: True
Explanation: The path 5 → 4 → 11 → 2 has sum 22

Example 2:

Tree:
    1
   /
  2

target_sum = 1
Output: False
Explanation: Node 1 has a child, so it's not a leaf. The only complete path is 1 → 2, which sums to 3

Example 3:

Tree: (empty)
target_sum = 0
Output: False
Explanation: No paths exist in an empty tree

Important Notes

  • Nodes with exactly one child are not leaf nodes
  • Node values can be negative, so path sums may increase or decrease
  • An empty tree always returns False, even when target_sum is 0

Hints

Hint 1

Track the remaining sum needed as you traverse down rather than accumulating the total

Hint 2

Remember that only nodes with no children count as leaves—a node with one child must be traversed further

Hint 3

Consider using an iterative approach with a stack to avoid recursion depth limits in deeply skewed trees