-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBinaryTreePaths.java
More file actions
64 lines (52 loc) · 1.38 KB
/
BinaryTreePaths.java
File metadata and controls
64 lines (52 loc) · 1.38 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
/*
Given a binary tree, return all root-to-leaf paths from left to right.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
*/
// this code only handle root's key < 10
public String[] binaryTreePaths(TreeNode root) {
List<String> allPaths = new ArrayList<>();
StringBuilder curPath = new StringBuilder();
traverse(root, allPaths, curPath);
String[] res = new String[allPaths.size()];
int i = 0;
for (String path : allPaths) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < path.length(); j++) {
if (j != path.length() - 1) {
sb.append(path.charAt(j));
sb.append("->");
} else {
sb.append(path.charAt(j));
}
}
curPath.setLength(Math.max(curPath.length() - 2, 0));
res[i] = sb.toString();
i++;
}
return res;
}
private void traverse(TreeNode root, List<String> allPaths, StringBuilder curPath) {
// base case 1
if (root == null) {
return;
}
// base case 2: leaf
if (root.left == null && root.right == null) {
curPath.append(Integer.toString(root.key));
allPaths.add(curPath.toString());
curPath.setLength(Math.max(curPath.length() - 1, 0));
return;
}
// recursive rules
curPath.append(Integer.toString(root.key));
traverse(root.left, allPaths, curPath);
traverse(root.right, allPaths, curPath);
curPath.setLength(Math.max(curPath.length() - 1, 0));
}