-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBinaryTreePaths.java
More file actions
31 lines (30 loc) · 970 Bytes
/
BinaryTreePaths.java
File metadata and controls
31 lines (30 loc) · 970 Bytes
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreePaths {
public List<String> binaryTreePaths(TreeNode root) {
List<String> path = new ArrayList<>();
List<String> paths = new ArrayList<>();
if (root == null) return paths;
dfs(root, path, paths);
return paths;
}
public void dfs(TreeNode root, List<String> path, List<String> paths) {
if (root.left == null && root.right == null) {
path.add(String.valueOf(root.val));
paths.add(String.join("->", path));
path.remove(path.size() - 1);
return;
}
path.add(String.valueOf(root.val));
if (root.left != null) dfs(root.left, path, paths);
if (root.right != null) dfs(root.right, path, paths);
path.remove(path.size() - 1);
}
}