class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
if(root == null) return res;
recur(root, target, 0);
return res;
}
public void recur(TreeNode root, int target, int sum){
//截止条件
if(root == null) return;
path.offerLast(root.val);
sum += root.val;
if(root.left == null && root.right == null && sum == target){
res.add(new LinkedList<>(path));
}
recur(root.left, target, sum);
recur(root.right, target, sum);
path.pollLast();
sum -= root.val;
}
}
剑指 Offer 34. 二叉树中和为某一值的路径
路径和目标:Java算法实现树节点的路径和求解
最新推荐文章于 2025-12-06 07:43:37 发布
本文介绍了如何使用Java实现一个Solution类,用于解决树节点的路径和问题。通过递归遍历树结构,找到从根节点到叶子节点之和等于目标值的所有路径,并将结果存储在List<List<Integer>>中。关键代码展示了如何设置截止条件、路径追踪和回溯操作。

536

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



