剑指 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();
}
}
该博客介绍了如何在二叉树中找到从根节点到叶节点且和为目标值的路径。通过递归的helper方法,利用回溯法记录路径,并在路径和等于目标值且当前节点为叶节点时,将路径添加到结果列表中。最后返回所有满足条件的路径。
536

被折叠的 条评论
为什么被折叠?



