剑指 Offer 34. 二叉树中和为某一值的路径
思路
从根节点到叶节点的路径和等于目标值
需要获得路径,回溯即可,在最后回退
代码
class Solution {
List<List<Integer>> res=new ArrayList<>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
helper(root,target);
return res;
}
public void helper(TreeNode root,int target){
if(root==null)return;
path.add(root.val);
target-=root.val;
if(target==0&&root.left==null&&root.right==null){
res.add(new LinkedList(path));
}
helper(root.left,target);
helper(root.right,target);
path.removeLast();
}
}