Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Check if any root-to-leaf path equals a target sum

Determine whether a binary tree has any root-to-leaf path whose node values sum to a target.

Python practice15 minTrees & Binary TreesIntermediateLast updated March 29, 2026

Problem statement

Given the root of a binary tree and an integer target_sum, return True if the tree has any root-to-leaf path such that adding up all the values along the path equals target_sum. A leaf is a node with no children. If the tree is empty, return False.

Task

Implement a function that checks if there exists a root-to-leaf path in a binary tree with a given sum using recursion or iterative traversal.

Examples

Example 1

Input

root = TreeNode(5, TreeNode(4, TreeNode(11, TreeNode(7), TreeNode(2))), TreeNode(8, TreeNode(13), TreeNode(4, None, TreeNode(1)))); target_sum = 22

Output

True

One path 5 -> 4 -> 11 -> 2 sums to 22.

Input format

A function call has_path_sum(root, target_sum) where root is a TreeNode or None, and target_sum is an integer.

Output format

Return a boolean: True if a root-to-leaf path sums to target_sum, otherwise False.

Constraints

- Node values and target_sum are integers (may be negative). - The number of nodes in the tree is in a reasonable range for recursion depth for typical interview constraints.

Samples

Sample 1

Input

root = TreeNode(1, TreeNode(2)); target_sum = 3

Output

True

Path 1 -> 2 sums to 3.