0%

LeetCode-113

题目

结果

代码

这个应该叫回溯算法?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
private final List<List<Integer>> ans = new LinkedList<>();

public List<List<Integer>> pathSum(TreeNode root, int sum) {
dfs(root, new LinkedList<>(), sum);
return ans;
}

private void dfs(TreeNode root, List<Integer> path, int sum) {
// 停止递归
if (root == null) {
return;
}

// copy一份path备用,这样也许会多耗很多空间,我想jvm或者编译器应该对此有优化吧
List<Integer> branch = new LinkedList<>(path);
branch.add(root.val);
if (isLeaf(root) && branch.stream().reduce(0, Integer::sum) == sum) {
ans.add(branch);
return;
}

// 递归
dfs(root.left, branch, sum);
dfs(root.right, branch, sum);
}

// 判断是否为叶子结点
private boolean isLeaf(TreeNode node) {
return node.left == null && node.right == null;
}
}

复杂度

时间复杂度:>O(n),因为还求和了

空间复杂度:O(不计其数)