题目描述

题解
/**
* 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
* }
* }
*/
// DFS / 前序遍历
// 这道题非常像【Leetcode】112. 路径总和 ,不过稍微修改了一点,
// 如果想不出来可以先写一个112题的解,然后从它基础上改。
// 本题需要返回的是List<List<Integer>>类型的路径数组res,所以我们在遍历结点
// 值累加到pathSum之后,还要将遍历结点值存入List<Integer>类型的path数组中,
// 递归函数返回之后当前结点值要从pathSum中被减去,且当前结点值还要从path
// 中删除。
// 当记录的pathSum等于targetSum时,且root是叶节点时,将path存入res中。
// 递归结束,返回res即可。
//
// 执行用时:1 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:38.6 MB, 在所有 Java 提交中击败了85.71%的用户
class Solution {
int pathSum = 0
int targetSum
List<List<Integer>> res = new ArrayList<>()
List<Integer> path = new ArrayList<>()
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
this.targetSum = targetSum
pathSumPreOrder(root)
return res
}
public void pathSumPreOrder(TreeNode root) {
if (root == null)
return
path.add(root.val)
if (root.left == null && root.right == null && pathSum == targetSum) {
res.add( new ArrayList<>(path) )
}
pathSumPreOrder(root.left)
pathSumPreOrder(root.right)
path.remove(path.size() - 1)
}
}