-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbinary-tree-paths.java
37 lines (36 loc) · 1.16 KB
/
binary-tree-paths.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<String>();
if (root == null) return list;
list.add("");
binaryPaths(list, root);
return list;
}
public void binaryPaths(List<String> list, TreeNode root) {
if (root == null) return;
String cur = list.remove(list.size()-1);
// System.out.println("root.val= " + root.val + ", cur= " + cur + ", " + Arrays.toString(list.toArray()));
if (root.left == null && root.right == null) {
list.add(cur + String.valueOf(root.val));
return;
} else {
if (root.left != null) {
list.add(cur + String.valueOf(root.val) + "->");
binaryPaths(list, root.left);
}
if (root.right != null) {
list.add(cur + String.valueOf(root.val) + "->");
binaryPaths(list, root.right);
}
}
}
}