二叉树中和为某一值的路径
得到结果路径后需要用temp复制path的内容,并存储在res中,否则res中存储的只是引用
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findPath(TreeNode root, int sum) {
dfs(root, sum);
return res;
}
private void dfs(TreeNode root, int sum) {
if (root == null)
return;
sum -= root.val;
path.add(root.val);
if (root.left == null && root.right == null && sum == 0){
List<Integer> temp = new ArrayList<>(path);
res.add(temp);
}
dfs(root.left, sum);
dfs(root.right, sum);
path.remove(path.size() - 1);
}
}