113.路径总和II
方法一:深度优先搜素
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<List<Integer>> ans = new LinkedList<List<Integer>>();
Deque<Integer> path = new LinkedList<Integer>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
dfs(root,targetSum);
return ans;
}
public void dfs(TreeNode root,int targetSum){
if(root == null){
return;
}
path.offerLast(root.val);
targetSum -= root.val;
if(root.left == null && root.right == null && targetSum == 0){
ans.add(new LinkedList<Integer>(path));
}
dfs(root.left,targetSum);
dfs(root.right,targetSum);
path.pollLast();
}
}