forked from sauravgpt2/hacktoberfest36_2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Class5.java
114 lines (90 loc) · 2.52 KB
/
Class5.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
package Generic_Tree;
import java.io.*;
import java.util.*;
public class Class5 {
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){
// write your code here
// euler's left, on the way deep in the recursion, node's pre area
System.out.println("Node Pre " + node.data);
for(Node child: node.children){
// edge pre area
System.out.println("Edge Pre " + node.data + "--" + child.data);
traversals(child);
System.out.println("Edge Post " + node.data + "--" + child.data);
// edge post area
}
System.out.println("Node Post " + node.data);
// euler's right, on the way out in the recursion, node's post area
}
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);
traversals(root);
}
}