-
Notifications
You must be signed in to change notification settings - Fork 0
/
AllRootToLeafPaths.java
53 lines (45 loc) · 1.42 KB
/
AllRootToLeafPaths.java
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
48
49
50
51
52
53
/********************************************************************
Following is the class structure of the Node class:
class BinaryTreeNode {
int data;
BinaryTreeNode left;
BinaryTreeNode right;
BinaryTreeNode(int data) {
this.data = data;
this.left = null;
this.right = null;
}
};
********************************************************************/
import java.util.*;
public class Solution {
static boolean isLeaf(BinaryTreeNode root) {
if (root.left == null && root.right == null) return true;
return false;
}
static void dfs(BinaryTreeNode root, List<Integer> nodes, List<String> res) {
if (root == null) return;
nodes.add(root.data);
if (isLeaf(root)) {
String path = "";
for (int i = 0; i < nodes.size(); i++) {
if (i == nodes.size() - 1) {
path += nodes.get(i);
} else {
path += nodes.get(i) + " ";
}
}
res.add(path);
} else {
dfs(root.left, nodes, res);
dfs(root.right, nodes, res);
}
nodes.remove(nodes.size() - 1);
}
public static List<String> allRootToLeaf(BinaryTreeNode root) {
// Write your code here.
List<String> res = new ArrayList<>();
dfs(root, new ArrayList<>(), res);
return res;
}
}