-
Notifications
You must be signed in to change notification settings - Fork 29
/
Solution257.java
52 lines (41 loc) · 1.18 KB
/
Solution257.java
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
package binary_search_tree_problem;
import java.util.ArrayList;
import java.util.List;
/**
* 定义递归问题
* O(n)
* O(h)
*/
public class Solution257 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<String> binaryTreePaths(TreeNode root) {
ArrayList<String> res = new ArrayList<>();
if (root == null) {
return res;
}
if (root.left == null && root.right == null) {
res.add(Integer.toString(root.val));
return res;
}
List<String> leftPaths = binaryTreePaths(root.left);
for (String s:leftPaths) {
StringBuilder sb = new StringBuilder(Integer.toString(root.val));
sb.append("->");
sb.append(s);
res.add(sb.toString());
}
List<String> rightPaths = binaryTreePaths(root.right);
for (String s:rightPaths) {
StringBuilder sb = new StringBuilder(Integer.toString(root.val));
sb.append("->");
sb.append(s);
res.add(sb.toString());
}
return res;
}
}