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]
]
题意:是112题的followup,要求输出所有符合条件的路径。
思路:
在112题解法的框架上做一些改变。
增加一个list记录每次遍历的路径,这个list在回溯到上一个节点的时候需要把当前点从list中删除。
找到了满足条件的路径后,需要把这个路径的list加到结果集中,此时需要加一个new ArrayList,如果直接加传参的list,由于引用的性质会有bug。
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
dfs(root, sum, new ArrayList<>(), res);
return res;
}
public void dfs(TreeNode root, int sum, List<Integer> list, List<List<Integer>> res) {
list.add(root.val);
if (root.left == null && root.right == null) {
if (root.val == sum) {
res.add(new ArrayList<>(list));
}
list.remove(list.size() - 1);
return;
}
if (root.left != null) {
dfs(root.left, sum - root.val, list, res);
}
if (root.right != null) {
dfs(root.right, sum - root.val, list, res);
}
list.remove(list.size() - 1);
}