-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
50 lines (45 loc) · 1.31 KB
/
Solution.java
File metadata and controls
50 lines (45 loc) · 1.31 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
import java.util.ArrayList;
import java.util.List;
/**
* Created by wangzhan on 2016-05-31.
*/
public class Solution {
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
Solution instance = new Solution();
System.out.println(instance.binaryTreePaths(root));
}
public List<String> binaryTreePaths(TreeNode root) {
ArrayList<String> pathList = new ArrayList<>();
if (root == null)
return pathList;
String path = "";
childPaths(pathList, root, path);
return pathList;
}
private void childPaths(ArrayList<String> pathList, TreeNode root, String path) {
if (root == null)
return;
path += root.val;
if (root.left == null && root.right == null) {
pathList.add(path);
return;
} else {
childPaths(pathList, root.left, path+"->");
childPaths(pathList, root.right, path+"->");
}
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
this.right = this.left = null;
}
}