-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path127. RootToLeafPaths.java
More file actions
45 lines (35 loc) · 1.01 KB
/
127. RootToLeafPaths.java
File metadata and controls
45 lines (35 loc) · 1.01 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
/*
Definition for Binary Tree Node
class Node
{
int data;
Node left;
Node right;
Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
*/
class Solution {
public static ArrayList<ArrayList<Integer>> Paths(Node root) {
ArrayList<ArrayList<Integer>> allPaths = new ArrayList<>();
ArrayList<Integer> currentPath = new ArrayList<>();
findPaths(root, currentPath, allPaths);
return allPaths;
}
private static void findPaths(Node node, ArrayList<Integer> currentPath, ArrayList<ArrayList<Integer>> allPaths) {
if (node == null)
return;
currentPath.add(node.data);
if (node.left == null && node.right == null) {
allPaths.add(new ArrayList<>(currentPath));
} else {
findPaths(node.left, currentPath, allPaths);
findPaths(node.right, currentPath, allPaths);
}
currentPath.remove(currentPath.size() - 1);
}
}