-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0113_path_sum_II.java
More file actions
105 lines (88 loc) · 2.47 KB
/
0113_path_sum_II.java
File metadata and controls
105 lines (88 loc) · 2.47 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* https://leetcode-cn.com/problems/path-sum-ii/
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
-------------------------------------------------------------------------------------------------------------------------
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class MySolution {
private List<List<Integer>> paths;
private List<Integer> path;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
paths = new ArrayList<>();
path = new ArrayList<>();
helper(root, path, sum);
return paths;
}
private void helper(TreeNode node, List<Integer> path, int rem) {
if (node == null) return ;
path.add(node.val);
if (rem == node.val && node.left == null && node.right == null) {
paths.add(path);
}
else {
helper(node.left, new ArrayList<>(path), rem - node.val);
helper(node.right, new ArrayList<>(path), rem - node.val);
}
}
}
class Solution1 {
private List<List<Integer>> result;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
result = new LinkedList<>();
List<Integer> path = new ArrayList<>();
getPath(root, sum, path);
return result;
}
private void getPath(TreeNode root, int sum, List<Integer> path) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null && root.val - sum == 0) {
List<Integer> copy = new ArrayList<>(path);
result.add(copy);
}
getPath(root.left, sum - root.val, path);
getPath(root.right, sum - root.val, path);
path.remove(path.size() - 1);
}
}