Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of node values equals targetSum.
root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22[[5,4,11,2],[5,8,4,5]]root = [1,2,3], targetSum = 5[]path.add(node.val); rem -= node.valrem == 0 → add copy of path to resultpath.remove(last) — restore stateUnlike Path Sum I (stop at first match), we must find all paths. Backtracking lets us reuse a single path list: add a node on entry, explore both subtrees, then remove on exit. This gives O(h) space for the path instead of O(n) per path.
Copying the whole path at every node wastes memory and time. We can keep one shared path and undo each step on the way back.
Keep a path list and a remaining target. When you enter a node, add it to the path and subtract its value. At a leaf with remaining 0, save a copy of the path. When you leave a node, remove it from the path, which is the backtracking step.
Add on the way down, remove on the way back up. Only copy the path when you actually save it.
Run the animation above on your own input, or watch the 1:51 video explanation of Path Sum II with a dry run and Java code.