-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
50 lines (40 loc) · 1.1 KB
/
Copy pathPathSum.java
File metadata and controls
50 lines (40 loc) · 1.1 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package dfs_bfs;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class PathSum {
List<List<Integer>> res = new LinkedList<>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
// 深度优先遍历 targetSum -= root.val --> targetSum == 0 返回路径
dfs(root, targetSum);
return res;
}
private void dfs(TreeNode root, int targetSum) {
if (root == null)
return;
path.offerLast(root.val);
targetSum -= root.val;
if (targetSum == 0 && root.left == null && root.right == null) {
res.add(new LinkedList<Integer>(path));
}
dfs(root.left, targetSum);
dfs(root.right, targetSum);
path.pollLast();
}
}
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;
}
}