-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-paths.java
65 lines (56 loc) · 1.87 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
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/* public List<String> binaryTreePaths(TreeNode root) {
String cur = "";
List<String> result = new ArrayList<String>();
result = paths(root,result,cur);
return result;
}
public List<String> paths(TreeNode root, List<String> result, String cur){
if(root == null) return result;
if(root.left == null && root.right == null) cur = cur + root.val;
else cur = cur + root.val + "->";
if(root.left == null && root.right == null){
result.add(cur);
return result;
}
paths(root.left,result,cur);
paths(root.right,result,cur);
return result;
} */
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
String path = "";
paths = searchPaths(root,path,paths);
System.out.println(paths.toString());
return paths;
}
public List<String> searchPaths(TreeNode root,String path,List<String> sb) {
if(root==null) return sb;
if(root.left == null && root.right == null) {
path = path + Integer.toString(root.val);
}
else path = path +Integer.toString(root.val)+ "->";
if(root.left == null && root.right == null) {
sb.add(path);
return sb;
}
if(root.left != null) {
//path = path +Integer.toString(root.val)+ "->";
searchPaths(root.left,path,sb);
}
if(root.right != null) {
//path = path + Integer.toString(root.val)+ "->";
searchPaths(root.right,path,sb);
}
return sb;
}
}