Imagine navigating a maze where you want to find all routes from the entrance to the exit that add up to a certain score. This problem is about finding all root-to-leaf paths in a binary tree whose node values sum to a target.
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. A leaf is a node with no children. Each path should be returned as a list of the node values, and the collection of paths should be returned as a list of lists.
The number of nodes in the tree is in the range [1, 5000]-1000 <= Node.val <= 1000-1000 <= targetSum <= 1000000
Edge cases: Single node tree where node value equals targetSum → output is [[node.val]]Single node tree where node value does not equal targetSum → output is []Tree with negative values and targetSum that requires including negative nodes → output includes paths with negative values
def pathSum(root: Optional[TreeNode], targetSum: int) -> List[List[int]]:public List<List<Integer>> pathSum(TreeNode root, int targetSum)vector<vector<int>> pathSum(TreeNode* root, int targetSum)function pathSum(root, targetSum)
def pathSum(root, targetSum):
# Write your solution here
pass
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
// Write your solution here
return new ArrayList<>();
}
}
#include <vector>
using namespace std;
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
// Write your solution here
return {};
}
function pathSum(root, targetSum) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: [[5,4,11]]Adding paths before confirming leaf node, missing last node in path.✅ Add path to results only if node.left == null and node.right == null.
Wrong: [[1]]Returning path even when single node value != targetSum.✅ Check if root.val == targetSum before adding path for single node tree.
Wrong: [[1,2]]Including partial paths that are not root-to-leaf.✅ Add paths only at leaf nodes, not intermediate nodes.
Wrong: []Pruning paths too early when negative values are present.✅ Do not prune paths based on partial sums; allow negative values in path sums.
Wrong: Partial or missing pathsGreedy pruning stops search after first valid path found.✅ Explore all paths fully using backtracking without early stopping.