题目描述
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
lc练习
实现
- 参考:lc
- 复杂度分析
时间复杂度:O(N^2) n的平方
空间复杂度:O(N)
List<List<Integer>> res = new ArrayList<>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
// if (root == null || targetSum == 0) return res; //无需判断,正负会相加会为0 [7,0,null,-1,-6,null,1,null,null,-7] 0
dfs(root, targetSum);
return res;
}
public void dfs(TreeNode root, int sum) {
if (root == null) return;
path.offerLast(root.val);
sum -= root.val;
if (root.left == null && root.right == null && sum == 0) {
res.add(new LinkedList<>(path));
}
dfs(root.left, sum);
dfs(root.right, sum);
path.pollLast();
}