-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathBinaryTreePaths.java
More file actions
33 lines (26 loc) · 896 Bytes
/
BinaryTreePaths.java
File metadata and controls
33 lines (26 loc) · 896 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
30
31
32
33
import java.util.ArrayList;
import java.util.List;
public class BinaryTreePaths {
public static List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
binaryTreePaths(root, new ArrayList<>(), result);
return result;
}
private static void binaryTreePaths(TreeNode root, List<CharSequence> path, List<String> paths) {
if (root == null) {
return;
}
path.add(root.val + "");
if (isLeafNode(root)) {
paths.add(String.join("->", path));
path.remove(path.size() - 1);
return;
}
binaryTreePaths(root.left, path, paths);
binaryTreePaths(root.right, path, paths);
path.remove(path.size() - 1);
}
private static boolean isLeafNode(TreeNode root) {
return root.left == null && root.right == null;
}
}