-
Notifications
You must be signed in to change notification settings - Fork 17
/
Implementation.java
61 lines (47 loc) · 1.35 KB
/
Implementation.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
54
55
56
57
58
59
60
61
import java.util.*;
public class Main {
private static class Node {
int data;
ArrayList<Node> children = new ArrayList<>();
}
public static void display(Node node) {
String str = node.data + " -> ";
for (Node child : node.children) {
str += child.data + ", ";
}
str += ".";
System.out.println(str);
for (Node child : node.children) {
display(child);
}
}
public static int size(Node node) {
int s = 0;
for(Node child: node.children) {
s += size(child);
}
s = s+1;
return s;
}
public static void main(String args[]) {
int arr[] = {10, 20, 50, -1, 60, -1, -1, 30, 70, -1, 80, 110, -1, 120, -1, -1, 90, -1, -1, 40, 100, -1, -1, -1};
Stack<Node> st = new Stack<>();
Node root = null;
for(int i=0; i<arr.length; i++) {
if(arr[i] != -1) {
Node toAdd = new Node();
toAdd.data = arr[i];
if(st.isEmpty()) {
root = toAdd;
} else {
st.peek().children.add(toAdd);
}
st.push(toAdd);
} else {
st.pop();
}
}
// display(root);
System.out.println(size(root));
}
}