剑指 Offer 34. 二叉树中和为某一值的路径
回溯(先序遍历)
遍历从根节点到叶子节点的每一条路径,当遍历到叶子节点(root.left == null && root.right == null)时,且此时路径和为 target 时,我们就找到了一条满足条件的路径,将些路径加入结果列表。
class Solution {
LinkedList<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
recur(root, target);
return res;
}
private void recur(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(path),path变化时,res中的path也会变化
res.add(new LinkedList(path));
}
recur(root.left, target);
recur(root.right, target);
path.removeLast(); // 向上回溯前,需要将当前节点从路径中删除
}
}