- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1600.java
72 lines (63 loc) · 2.34 KB
/
_1600.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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
publicclass_1600 {
publicstaticclassSolution1 {
/*
* My completely original solution:
* 1. use a tree structure to represent the king family;
* 2. then use preorder traversal to find the inheritance order;
* 3. use a map to quickly find the corresponding node in the tree based on the name since all names are distinct
*/
publicstaticclassPerson {
List<Person> children;
Stringname;
booleanisAlive;
publicPerson(StringkingName) {
this.name = kingName;
this.children = newArrayList<>();
this.isAlive = true;
}
}
publicstaticclassThroneInheritance {
Personking;
Map<String, Person> map;
StringkingName;
publicThroneInheritance(StringkingName) {
king = newPerson(kingName);
map = newHashMap<>();
this.kingName = kingName;
map.put(kingName, king);
}
publicvoidbirth(StringparentName, StringchildName) {
PersonparentNode = map.getOrDefault(parentName, newPerson(parentName));
Personchild = newPerson(childName);
parentNode.children.add(child);
map.put(parentName, parentNode);
map.put(childName, child);
}
publicvoiddeath(Stringname) {
PersondeadPerson = map.get(name);
deadPerson.isAlive = false;
map.put(name, deadPerson);
}
publicList<String> getInheritanceOrder() {
returnpreorder(map.get(this.kingName), newArrayList<>());
}
privateList<String> preorder(Personperson, List<String> list) {
if (person == null) {
returnlist;
}
if (person.isAlive) {
list.add(person.name);
}
for (Personchild : person.children) {
preorder(child, list);
}
returnlist;
}
}
}
}