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在回溯到上一個節(jié)點(diǎn)的時候需要把當(dāng)前點(diǎn)從list中刪除。
找到了滿足條件的路徑后,需要把這個路徑的list加到結(jié)果集中,此時需要加一個new ArrayList,如果直接加傳參的list,由于引用的性質(zhì)會有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);
}