Root-to-Leaf Paths with a Target Sum
Problem statement
Given the root of a binary tree and an integer targetSum, return every root-to-leaf path whose node values add up to targetSum.
A leaf has no children. Return paths in left-to-right depth-first order, with each path listed from the root to its leaf.
Function
pathSum(root: TreeNode, targetSum: int) → int[][]Examples
Example 1
root = [5,4,8,11,null,13,4,7,2,null,null,5,1]targetSum = 22return = [[5,4,11,2],[5,8,4,5]]Both listed root-to-leaf paths sum to 22, and the left path is visited first.
Example 2
root = [1,2,3]targetSum = 5return = []Neither root-to-leaf path sums to 5.
Example 3
root = []targetSum = 0return = []An empty tree has no root-to-leaf path.
Constraints
- The tree contains between
0and500nodes. -1000 ≤ Node.val ≤ 1000.-10^9 ≤ targetSum ≤ 10^9.