113. Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:vGiven the below binary tree andsum = 22
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
思路:DFS递归,非常经典
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
DFS(root, res, temp, sum, 0);
return res;
}
public void DFS(TreeNode root, List<List<Integer>> res, List<Integer> temp, int sum, int currSum){
if (root == null){
return;
}
temp.add(root.val);
if (root.left==null && root.right==null && currSum+root.val==sum){
res.add(new ArrayList<Integer>(temp));
}else{
DFS(root.left, res, temp, sum, currSum+root.val);
DFS(root.right, res, temp, sum, currSum+root.val);
}
temp.remove(temp.size() - 1);
}
}