url:
https://leetcode.com/problems/path-sum-ii/description/
描述:
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]
]
解题思路:
深度优先搜索
示例代码:
class Solution {
private List<List<Integer>> res = new ArrayList();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
dfs(sum,root,new ArrayList<Integer>());
return res;
}
private void dfs(int sum,TreeNode root,List<Integer> temp){
if(root==null) return;
if(sum-root.val==0&&root.left==null&&root.right==null){
temp.add(root.val);
res.add(new ArrayList(temp));
}else if(sum>0||root!=null){
temp.add(root.val);
dfs(sum-root.val,root.left,temp);
dfs(sum-root.val,root.right,temp);
}
temp.remove(temp.size()-1);
}
}