-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-paths.java
More file actions
29 lines (25 loc) · 904 Bytes
/
Copy pathbinary-tree-paths.java
File metadata and controls
29 lines (25 loc) · 904 Bytes
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
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root != null) dfs(root, new ArrayList<>(), result);
return result;
}
private void dfs(TreeNode node, List<Integer> path, List<String> result) {
path.add(node.val);
if (node.left == null && node.right == null)
result.add(makePath(path));
else {
if (node.left != null) dfs(node.left, path, result);
if (node.right != null) dfs(node.right, path, result);
}
path.remove(path.size() - 1); // backtrack
}
private String makePath(List<Integer> path) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size(); i++) {
if (i > 0) sb.append("->");
sb.append(path.get(i));
}
return sb.toString();
}
}