forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePaths.java
More file actions
46 lines (37 loc) · 988 Bytes
/
BinaryTreePaths.java
File metadata and controls
46 lines (37 loc) · 988 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.thealgorithms.backtracking;
import java.util.ArrayList;
import java.util.List;
public class BinaryTreePaths {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
if (root == null) {
return list;
}
dfs(root, "", list);
return list;
}
private void dfs(TreeNode node, String path, List<String> list) {
if (node == null) {
return;
}
if (path.isEmpty()) {
path = Integer.toString(node.val);
} else {
path += "->" + node.val;
}
if (node.left == null && node.right == null) {
list.add(path);
return;
}
dfs(node.left, path, list);
dfs(node.right, path, list);
}
}