Problem · Tree
Binary Tree Target-Sum Paths
Learn this problemProblem 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 is a node with no left child and no right child. Each returned path lists its values from the root to that leaf.
Return qualifying paths in left-to-right depth-first order: completely visit a node's left subtree before its right subtree.
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]]The two left-to-right root-to-leaf paths with sum 22 are 5 → 4 → 11 → 2 and 5 → 8 → 4 → 5.
Example 2
root = [1,2,3]targetSum = 5return = []The two root-to-leaf sums are 3 and 4, so neither path qualifies.
Example 3
root = []targetSum = 0return = []An empty tree has no root-to-leaf paths.
Constraints
- The tree contains at most
5000nodes. - Each node value is between
-1000and1000, inclusive. -10^9 <= targetSum <= 10^9.