forked from starrohan999/Hacktoberfest-Accepted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClass7.java
132 lines (103 loc) · 2.82 KB
/
Class7.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package Generic_Tree;
import java.io.*;
import java.util.*;
public class Class7 {
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 Node construct(int[] arr) {
Node root = null;
Stack<Node> st = new Stack<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1) {
st.pop();
} else {
Node t = new Node();
t.data = arr[i];
if (st.size() > 0) {
st.peek().children.add(t);
} else {
root = t;
}
st.push(t);
}
}
return root;
}
public static int size(Node node) {
int s = 0;
for (Node child : node.children) {
s += size(child);
}
s += 1;
return s;
}
public static int max(Node node) {
int m = Integer.MIN_VALUE;
for (Node child : node.children) {
int cm = max(child);
m = Math.max(m, cm);
}
m = Math.max(m, node.data);
return m;
}
public static int height(Node node) {
int h = -1;
for (Node child : node.children) {
int ch = height(child);
h = Math.max(h, ch);
}
h += 1;
return h;
}
public static void traversals(Node node){
System.out.println("Node Pre " + node.data);
for(Node child: node.children){
System.out.println("Edge Pre " + node.data + "--" + child.data);
traversals(child);
System.out.println("Edge Post " + node.data + "--" + child.data);
}
System.out.println("Node Post " + node.data);
}
public static void levelOrderLinewise(Node node){
// write your code here
Queue<Node> mq = new ArrayDeque<>();
mq.add(node);
Queue<Node> cq = new ArrayDeque<>();
while(mq.size()>0){
node = mq.remove();
System.out.print(node.data+" ");
for(Node child: node.children){
cq.add(child);
}
if(mq.size() == 0){
mq = cq;
cq = new ArrayDeque<>();
System.out.println();
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] values = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(values[i]);
}
Node root = construct(arr);
levelOrderLinewise(root);
}
}