Repository navigation
Expand file tree
/
Copy pathBinaryTreePaths.java
More file actions
65 lines (54 loc) · 1.68 KB
/
Copy pathBinaryTreePaths.java
File metadata and controls
65 lines (54 loc) · 1.68 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
package problems.easy;
import java.util.ArrayList;
import java.util.List;
import problems.utils.TreeNode;
/**
* Created by sherxon on 2016-12-30.
*/
public class BinaryTreePaths {
public List<String> binaryTreePaths(TreeNode root) {
if(root == null )return new ArrayList<>();
List<String> r=new ArrayList<>();
if(root.left!=null){
List<String> s=binaryTreePaths(root.left);
for(String str:s)
r.add(root.val +"->" +str);
}
if(root.right!=null){
List<String> s=binaryTreePaths(root.right);
for(String str:s)
r.add(root.val +"->" +str);
}
if(root.left==null && root.right==null)
r.add(0, root.val + "");
return r;
}
/**
* This is recursive solution with StringBuilder
*/
public List<String> binaryTreePaths2(TreeNode root) {
List<String> list = new ArrayList<>();
if (root == null) {
return list;
}
StringBuilder sb = new StringBuilder();
sb.append(root.val + "");
if (root.left == null && root.right == null) {
list.add(sb.toString());
}
go(list, root.left, new StringBuilder(sb));
go(list, root.right, new StringBuilder(sb));
return list;
}
void go(List<String> list, TreeNode root, StringBuilder sb) {
if (root == null) {
return;
}
sb.append("->").append(root.val);
if (root.left == null && root.right == null) {
list.add(sb.toString());
}
go(list, root.left, new StringBuilder(sb));
go(list, root.right, new StringBuilder(sb));
}
}