FastPrepRoot-to-Leaf Paths with a Target Sum
Problems/Root-to-Leaf Paths with a Target Sum

Root-to-Leaf Paths with a Target Sum

Amazon logoAmazon● MediumNEW GRADONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: Reported in an Amazon new-grad onsite interview as Path Sum II. The source does not specify a tree encoding, empty-tree behavior, output order, or input bounds; this practice version uses a nullable level-order tree, returns matching paths in left-to-right depth-first order, and caps trees at 500 nodes with bounded node and target values. Problem match confidence: approximately 99%.

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

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 Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon 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…