Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

All Paths With Given Sum

Medium Acceptance 74.23% Points 30

You are given the root of a binary tree and an integer targetSum. Your task is to find all root-to-leaf paths where the sum of the node values along the path equals targetSum.

A valid path must:

  • Start at the root node.
  • End at a leaf node.
  • Have a total sum equal to targetSum.

Return a list containing all such paths.

Examples
Example 1

image Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: Two root-to-leaf paths sum to 22: 5 → 4 → 11 → 2 and 5 → 8 → 4 → 5.

Example 2

image Input: root = [1,2,3], targetSum = 5
Output: []
Explanation: No root-to-leaf path has a sum equal to 5.

Example 3

image Input: root = [], targetSum = 0
Output: []
Explanation: An empty tree has no paths.

Constraints
    • 0 = Number of nodes = 5000
    • -10? = Node.data = 10?
    • -10? = targetSum = 10?
Topics
Tree Traversal Binary Tree
Companies
ZScaler Media.net
Added 08 Aug 2026 74.23% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 4 5 6 7
11