class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if(root == null) return new LinkedList<>();
List<List<Integer>> arr = new LinkedList<>();
LinkedList<Integer> arr1 = new LinkedList<Integer>();
dfs(root, arr, arr1, targetSum, 0);
return arr;
}
static void dfs(TreeNode root, List<List<Integer>> arr,LinkedList arr1, int targetSum, int count){
count += root.val;
arr1.add(root.val);
if(targetSum == count && root.left == null && root.right == null){
arr.add(new LinkedList(arr1));
}
if(root.left != null){
dfs(root.left, arr, arr1, targetSum, count);
}
if(root.right != null){
dfs(root.right, arr, arr1, targetSum, count);
}
arr1.removeLast();
}
}
随便去刷的一题,今天没怎么看算法,所以就在力扣找一题中等难度的深搜玩一玩(难的我也不一定会啊)
简单说一下题目
因为递归深搜的终止条件是 路径和等于targetSum,同时满足这个节点是叶子节点,也就是左右子节点为空了
List选择使用的LinkedList,因为要频繁插入删除,所以感觉链表效率会高一些
还有一件事,arr.add(arr1)是不行的,必须生成一个新的对象添加到arr中,因为如果你不生成一个新的对象,我们后续对
arr1的操作会影响到之前已经添加进去的链表,因为添加进链表的只是地址。