MediumBacktrackingTreeDepth-First SearchBinary Tree

Path Sum II

LeetCode
1 approach, code in all languages

You are given the root of a binary tree together with an integer targetSum. A root-to-leaf path is a sequence of nodes that begins at the root and ends at a leaf, moving only from a parent to one of its children.

Return every root-to-leaf path whose node values add up exactly to targetSum. Each qualifying path should be returned as the list of node values encountered along the way, and the paths themselves may be returned in any order.

A leaf is a node that has no children. If no path reaches the target, return an empty list.

Example 1

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]]

Two root-to-leaf paths sum to 22: 5 -> 4 -> 11 -> 2 and 5 -> 8 -> 4 -> 5.

Example 2

Input: root = [1,2,3], targetSum = 5

Output: []

The root-to-leaf paths sum to 3 (1 -> 2) and 4 (1 -> 3); neither reaches 5.

Constraints

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now