-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
51 lines (45 loc) · 1.05 KB
/
Copy pathSolution.java
File metadata and controls
51 lines (45 loc) · 1.05 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
51
import java.util.ArrayList;
import java.util.List;
public class Solution
{
public List<String> binaryTreePaths(TreeNode root)
{
List<String> list = new ArrayList<String>();
getPaths(root, list);
return list;
}
private void getPaths(TreeNode root, List<String> list)
{
if (root == null)
{
return;
}
if (root.left == null && root.right == null)
{
list.add("" + root.val);
return;
}
List<String> left = new ArrayList<String>();
List<String> right = new ArrayList<String>();
getPaths(root.left, left);
getPaths(root.right, right);
for (String path : left)
{
list.add(root.val + "->" + path);
}
for (String path : right)
{
list.add(root.val + "->" + path);
}
}
public static class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x)
{
val = x;
}
}
}