题目
题解
先序遍历+回溯、找到满足条件的路径,注意的是添加结果结合的时候要新建一个集合。
大佬详细题解:面试题34. 二叉树中和为某一值的路径(回溯法,清晰图解)
/**
* 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 {
private List<List<Integer>> res = new ArrayList<>();
private ArrayList<Integer> cur = new ArrayList<>();
private Integer s = 0;
public List<List<Integer>> pathSum(TreeNode root, int target) {
if (root == null){
return new ArrayList<>();
}
dfs(root,target);
return res;
}
void dfs(TreeNode root, int target){
cur.add(root.val);
s += root.val;
if (root.left == null && root.right == null && s == target){
res.add(new ArrayList<>(cur));
cur.remove(cur.size()-1);
s -= root.val;
return;
}
if (root.left != null){
dfs(root.left,target);
}
if (root.right != null){
dfs(root.right,target);
}
cur.remove(cur.size()-1);
s -= root.val;
}
}