Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

All Paths With Given Sum

Medium Acceptance 74.23% Points 30.00

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?
Companies
ZScaler Media.net
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions