FastPrepRoot-to-Leaf Paths with a Target Sum

Root-to-Leaf Paths with a Target Sum

Bloomberg LP logoBloomberg LP● MediumNEW GRADONSITE INTERVIEW

Updated

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) → List<List<Integer>>

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

Both listed root-to-leaf paths sum to 22, and the left path is visited first.

Example 2

root = [1,2,3]targetSum = 5return = []
root
123

Neither root-to-leaf path sums to 5.

Example 3

root = []targetSum = 0return = []
root
empty

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 Onsite Interview questions

Similar questions at other companies

Interview reports that mention this question

Bloomberg LP interview experiences

All Bloomberg LP interview questionsSee Bloomberg LP hiring insights
Saved
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        // write your code here
    }

}
Checking account…