题目链接:二叉树中和为某一值的路径
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param target int整型
* @return int整型ArrayList<ArrayList<>>
*/
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
ArrayList<Integer> path = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath (TreeNode root, int sum) {
if(root == null) return res;
dfs(root, sum);
return res;
}
public void dfs(TreeNode root, int sum){
if(root == null) return ;
path.add(root.val);
sum -= root.val;
if(root.left == null && root.right == null && sum == 0) res.add(new ArrayList<>(path));
dfs(root.left, sum);
dfs(root.right, sum);
path.remove(path.size() - 1);
}
}