forked from int28h/JavaTasks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree-height.java
More file actions
199 lines (173 loc) · 4.59 KB
/
tree-height.java
File metadata and controls
199 lines (173 loc) · 4.59 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
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/*
Формата ввода.
Первая строка содержит натуральное число n.
Вторая строка содержит n целых неотрицательных чисел parent[0]...parentn[n-1].
Для каждого 0 <= i <= n-1, parent[i] — родитель вершины i;
если parent[i] = -1, то i является корнем.
Гарантируется, что корень ровно один. Гарантируется, что данная последовательность задает дерево.
Формат вывода.
Высота дерева.
Sample Input:
10
9 7 5 5 2 9 9 9 2 -1
Sample Output:
4
Sample Input:
5
4 -1 4 1 1
Sample Output:
3
Sample Input:
5
-1 0 4 0 3
Sample Output:
4
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class TreeHeight {
private List<Node> tree;
private Node root;
private static class Node {
Node parent;
List<Node> children = new LinkedList<Node>();
int key, parentKey;
private Node(int key) {
this.key = key;
}
public Node getParent() {
return parent;
}
public int getKey() {
return key;
}
private int getParentKey() {
return parentKey;
}
public List<Node> getChildren(){
return children;
}
}
public TreeHeight() {
this.tree = new LinkedList<>();
}
/**
* Получение корня дерева
* @return
*/
public Node getRoot() {
return root;
}
/**
* Получение узла дерева по его ключу
* @param key
* @return
*/
public Node getByKey(int key) {
Node x = null;
for(Node n : tree) {
if(n.getKey() == key) {
x = n;
break;
}
}
return x;
}
/**
* Добавление узла в дерево
* @param key
* @param parentKey
*/
private void addNode(int key, int parentKey) {
if(parentKey == -1) {
this.root = new Node(key);
tree.add(root);
//System.out.println("Добавлен корень с ключом " + key);
} else {
Node current = new Node(key);
tree.add(current);
current.parentKey = parentKey;
//System.out.println("Добавлен узел с ключом " + key);
}
}
/**
* Установление связей между узлами
*/
private void setContacts() {
for(Node n : tree) {
if(n != root) {
n.parent = getByKey(n.getParentKey());
n.getParent().getChildren().add(n);
}
}
}
/**
* Вывод данных о каждом из узлов дерева
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for(Node n : tree) {
result.append("Узел с ключом " + n.getKey());
if(n.getParent() != null) {
result.append(", родитель - узел с ключом " + n.getParent().getKey());
} else {
result.append(", корневой узел");
}
if(!n.getChildren().isEmpty()) {
result.append(", потомки - ");
for(Node ch : n.getChildren()) {
result.append(ch.getKey() + ", ");
}
result.append("\n");
} else {
result.append(", потомков нет" + "\n");
}
}
return result.toString();
}
/**
* Получение высоты для заданного узла
* @param node
* @return
*/
public int getHeight(Node node) {
if(node == null) return 0;
int childrenCount = node.children.size();
ArrayList<Integer> heightes = new ArrayList<>();
for(int i = 0; i < childrenCount; i++) {
heightes.add(getHeight(node.getChildren().get(i)));
}
if(!heightes.isEmpty()) {
return 1 + Collections.max(heightes);
} else {
return 1;
}
}
public static void main(final String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int nodesCount = in.nextInt();
TreeHeight tree = new TreeHeight();
Map<Integer, Integer> nodes = new HashMap<>();
for(int i = 0; i < nodesCount; i++) {
nodes.put(i, in.nextInt()); //пара ключ + ключ родителя
}
//посмотреть на считанные данные
//System.out.println(nodes.toString());
//проход по хешмапе, создание узлов
for(Entry<Integer, Integer> m : nodes.entrySet()) {
tree.addNode(m.getKey(), m.getValue());
}
//связывание узлов в дерево
tree.setContacts();
//посмотреть что получилось
//System.out.println(tree.toString());
System.out.println(tree.getHeight(tree.getRoot()));
}
}