-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreePaths.java
More file actions
42 lines (37 loc) · 1.08 KB
/
Copy pathbinaryTreePaths.java
File metadata and controls
42 lines (37 loc) · 1.08 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
/* Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children. */
import java.util.ArrayList;
import java.util.List;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<>();
if (root != null) {
dfs(root, "", paths);
}
return paths;
}
private void dfs(TreeNode node, String currentPath, List<String> paths) {
if (node.left == null && node.right == null) {
paths.add(currentPath + node.val);
return;
}
if (node.left != null) {
dfs(node.left, currentPath + node.val + "->", paths);
}
if (node.right != null) {
dfs(node.right, currentPath + node.val + "->", paths);
}
}
}