Description:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Code:
class Solution {
private List<List<Integer>> paths = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
traverse(root, sum, new ArrayList<Integer>());
return paths;
}
private void traverse(TreeNode root, int sum, ArrayList<Integer> path) {
if (root != null) {
path.add(root.val);
if (root.left == null && root.right == null && sum == root.val) {
paths.add((ArrayList) path.clone());
}
traverse(root.left, sum - root.val, path);
traverse(root.right, sum - root.val, path);
path.remove(path.size() - 1);
}
}
}