Root-to-leaf equals target
boolean hasPathSum(Node n, int target) {
if (n == null) return false;
if (n.left == null && n.right == null) return n.val == target;
return hasPathSum(n.left, target - n.val) || hasPathSum(n.right, target - n.val);
}Advertisement
All root-to-leaf paths with sum
void allPaths(Node n, int target, List cur, List> result) {
if (n == null) return;
cur.add(n.val);
if (n.left == null && n.right == null && target == n.val) result.add(new ArrayList<>(cur));
allPaths(n.left, target - n.val, cur, result);
allPaths(n.right, target - n.val, cur, result);
cur.remove(cur.size() - 1);
}
Advertisement
Count paths (any→any) with sum
Prefix-sum HashMap. At each node, look for prefixSum - target in the map. Update map before recursing, remove after (backtrack).