FastPrepRoot-to-Leaf Paths with a Target Sum

Root-to-Leaf Paths with a Target Sum

Bloomberg LP logoBloomberg LP● MediumNEW GRADONSITE INTERVIEW
Learn

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 0 and 500 nodes.
  • -1000 ≤ Node.val ≤ 1000.
  • -10^9 ≤ targetSum ≤ 10^9.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int[][] pathSum(TreeNode root, int targetSum) {
    // write your code here
}
root[5,4,8,11,null,13,4,7,2,null,null,5,1]
targetSum22
expected[[5,4,11,2],[5,8,4,5]]
Checking account…