Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
47 lines (38 loc) · 1.32 KB

File metadata and controls

47 lines (38 loc) · 1.32 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package Algorithms.tree;
import java.util.ArrayList;
import java.util.List;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class PathSum2 {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
pathSumHelp(root, sum, path, ret);
return ret;
}
public void pathSumHelp(TreeNode root, int sum, ArrayList<Integer> path, List<List<Integer>> ret) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null
&& root.right == null
&& root.val == sum) {
ret.add(new ArrayList<Integer>(path));
} else {
// 继续递归
pathSumHelp(root.left, sum - root.val, path, ret);
pathSumHelp(root.right, sum - root.val, path, ret);
}
// 注意,递归和回溯的特点就是 递归不可以改变path的值。也就是说,你返回时,这个path不能被改变
// 所以在这里要执行remove操作。
path.remove(path.size() - 1);
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.