AAlgoLoopSpaced repetition for LeetCode
EASYBFS / DFSLeetCode ↗

Path Sum

The key idea

Carry the remaining target down the tree: subtract each node's value as you descend. A path works exactly when you reach a leaf and the remaining target is exactly that leaf's value (so it hits zero there). Only leaves count as path ends, never internal nodes.

Problem

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. Return false otherwise.

A leaf is a node with no children. A root-to-leaf path starts at the root and ends at any leaf, following parent-to-child links the whole way down.

Constraints

Examples

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true
Input: root = [1,2,3], targetSum = 5 Output: false
Input: root = [], targetSum = 0 Output: false

Complexity

Time: O(n) Space: O(h)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems