113. Path Sum II
Asked at 10Bloomberg36Microsoft33Amazon29Meta29Google21Salesforce28Arista Networks60Palo Alto Networks50Oracle27TikTok26
Problem
Return every root-to-leaf path (as a list of node values) whose values add up to targetSum.
Example: [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 → [[5,4,11,2],[5,8,4,5]]
DFS with a path list; at a leaf with the right remainder, copy the path. Pop on the way back (backtracking).
Complexity: O(n²) worst case (copying paths).
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
res, path = [], []
def dfs(node, rest):
if not node:
return
path.append(node.val)
rest -= node.val
if not node.left and not node.right and rest == 0:
res.append(path[:])
dfs(node.left, rest)
dfs(node.right, rest)
path.pop()
dfs(root, targetSum)
return res
t = make_tree([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1])
assert sorted(Solution().pathSum(t, 22)) == sorted([[5, 4, 11, 2], [5, 8, 4, 5]])
assert Solution().pathSum(make_tree([1, 2, 3]), 5) == []
assert Solution().pathSum(make_tree([1, 2]), 0) == []
assert Solution().pathSum(make_tree([-2, None, -3]), -5) == [[-2, -3]]
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
dfs(root, targetSum, new ArrayList<>(), res);
return res;
}
private void dfs(TreeNode n, int rest, List<Integer> path, List<List<Integer>> res) {
if (n == null) return;
path.add(n.val);
rest -= n.val;
if (n.left == null && n.right == null && rest == 0) res.add(new ArrayList<>(path));
dfs(n.left, rest, path, res);
dfs(n.right, rest, path, res);
path.remove(path.size() - 1);
}
}
func pathSum(root *TreeNode, targetSum int) [][]int {
res, path := [][]int{}, []int{}
var dfs func(node *TreeNode, rest int)
dfs = func(node *TreeNode, rest int) {
if node == nil {
return
}
path = append(path, node.Val)
rest -= node.Val
if node.Left == nil && node.Right == nil && rest == 0 {
res = append(res, append([]int{}, path...)) // copy: path keeps changing
}
dfs(node.Left, rest)
dfs(node.Right, rest)
path = path[:len(path)-1]
}
dfs(root, targetSum)
return res
}