Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
和1一样用DFS, 只是这次要储存途径的点,用一个临时的 subList 来储存途径的点,当成功找到一条path后,将此 subList copy to new list and add to result. 如此反复利用这个临时的 list.
用BFS也可以,需要额外空间。
public static ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> totalList = new ArrayList<>();
ArrayList<Integer> subList = new ArrayList<>();
pathSumHelper(root, sum, subList, totalList);
return totalList;
}
private static void pathSumHelper(TreeNode root, int sum, ArrayList<Integer> subList, ArrayList<ArrayList<Integer>> totalList) {
if (root == null) return;
if (root.left == null && root.right == null && sum - root.val == 0) {
subList.add(root.val);
totalList.add(new ArrayList<Integer>(subList));
subList.remove(subList.size() - 1);
return;
}
subList.add(root.val);
pathSumHelper(root.left, sum - root.val, subList, totalList);
pathSumHelper(root.right, sum - root.val, subList, totalList);
subList.remove(subList.size() - 1);
}