leetcode-113 路径总和 II
这个题是leetcode-112 路径总和的进阶,只需要额外开个数组记录路径。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<List<Integer>> res = new ArrayList<>();
private List<Integer> list = new ArrayList<>();
public void findPath(TreeNode root, int curSum, int aim){
if (root.left == null && root.right == null){
list.add(root.val);
if (curSum + root.val == aim){
// 不能直接把list加入,必须重新构建一个对象
res.add(new ArrayList<>(list));
}
list.remove(list.size() - 1);
return ;
}
list.add(root.val);
if (root.left != null) findPath(root.left, curSum + root.val, aim);
if (root.right != null) findPath(root.right, curSum + root.val, aim);
list.remove(list.size() - 1);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null) return res;
findPath(root, 0, sum);
return res;
}
}