- 算法
回溯和深度优先搜索 - 核心思想
二叉树很适合用深度优先搜索去做,简单快捷。
这道题值得注意点是必须从根到叶子,同时没必要减枝,减枝的条件也有点复杂。 - 代码
class Solution {
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if(root == null) return res;
LinkedList<Integer> temp = new LinkedList<>();
temp.add(root.val);
dfs(root,targetSum,temp,root.val);
return res;
}
private void dfs(TreeNode root, int targetSum, LinkedList<Integer> temp,int sum) {
if(root.left == null && root.right == null && sum == targetSum){
res.add(new LinkedList<>(temp));
return;
}
if(root.left != null){
TreeNode left = root.left;
temp.add(left.val);
dfs(left,targetSum,temp,sum + left.val);
temp.removeLast();
}
if (root.right != null){
TreeNode right = root.right;
temp.add(right.val);
dfs(right,targetSum,temp,sum + right.val);
temp.removeLast();
}
}
}