-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRootToLeafPaths.java
More file actions
48 lines (36 loc) · 1.13 KB
/
Copy pathRootToLeafPaths.java
File metadata and controls
48 lines (36 loc) · 1.13 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
package LeetcodePractice;
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class RootToLeafPaths {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root != null) dfs(root, "", result);
return result;
}
private void dfs(TreeNode node, String path, List<String> result) {
if (node.left == null && node.right == null) {
result.add(path + node.val);
return;
}
if (node.left != null) {
dfs(node.left, path + node.val + "->", result);
}
if (node.right != null) {
dfs(node.right, path + node.val + "->", result);
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(5);
RootToLeafPaths sol = new RootToLeafPaths();
List<String> paths = sol.binaryTreePaths(root);
System.out.println(paths);
}
}