-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathBinaryTreePaths.java
68 lines (55 loc) · 1.58 KB
/
BinaryTreePaths.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package problems.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* https://leetcode.com/problems/binary-tree-paths/
*/
public class BinaryTreePaths {
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
// root.left = new TreeNode(2);
// root.left.left = new TreeNode(4);
// root.left.right = new TreeNode(5);
// root.right = new TreeNode(3);
List<String> paths = new BinaryTreePaths().binaryTreePaths(root);
for (String path : paths) {
System.out.println(path);
}
}
private List<String> allPaths = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if (root != null) {
binaryTreePaths(root, new StringBuilder());
}
return allPaths;
}
private void binaryTreePaths(TreeNode node, StringBuilder path) {
int len = path.length();
if (path.length() > 0) {
path.append("->");
}
String str = String.valueOf(node.val);
path.append(str);
boolean leaf = true;
if (node.left != null) {
leaf = false;
binaryTreePaths(node.left, path);
}
if (node.right != null) {
leaf = false;
binaryTreePaths(node.right, path);
}
if (leaf) {
allPaths.add(path.toString());
}
path.setLength(len);
}
}