|
| 1 | +// https://leetcode.com/problems/throne-inheritance |
| 2 | +// N = people in royal family |
| 3 | +// birth() T: O(1) |
| 4 | +// death() T: O(1) |
| 5 | +// getInheritanceOrder T: O(N) |
| 6 | +// S: O(N) |
| 7 | + |
| 8 | +import java.util.ArrayList; |
| 9 | +import java.util.HashMap; |
| 10 | +import java.util.List; |
| 11 | +import java.util.Map; |
| 12 | + |
| 13 | +public class ThroneInheritance { |
| 14 | + private static final class Person { |
| 15 | + private final String name; |
| 16 | + private boolean isAlive = true; |
| 17 | + private final List<Person> children = new ArrayList<>(); |
| 18 | + |
| 19 | + Person(String name) { |
| 20 | + this.name = name; |
| 21 | + } |
| 22 | + |
| 23 | + void markDead() { |
| 24 | + this.isAlive = false; |
| 25 | + } |
| 26 | + |
| 27 | + void addChild(Person child) { |
| 28 | + this.children.add(child); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + private final Map<String, Person> royalFamily = new HashMap<>(); |
| 33 | + private final Person king; |
| 34 | + |
| 35 | + public ThroneInheritance(String kingName) { |
| 36 | + king = new Person(kingName); |
| 37 | + royalFamily.put(kingName, king); |
| 38 | + } |
| 39 | + |
| 40 | + public void birth(String parentName, String childName) { |
| 41 | + Person child = new Person(childName); |
| 42 | + royalFamily.put(childName, child); |
| 43 | + royalFamily.get(parentName).addChild(child); |
| 44 | + } |
| 45 | + |
| 46 | + public void death(String name) { |
| 47 | + royalFamily.get(name).markDead(); |
| 48 | + } |
| 49 | + |
| 50 | + public List<String> getInheritanceOrder() { |
| 51 | + final List<String> names = new ArrayList<>(); |
| 52 | + getInheritanceOrder(king, names); |
| 53 | + return names; |
| 54 | + } |
| 55 | + |
| 56 | + public void getInheritanceOrder(Person person, List<String> names) { |
| 57 | + if (person == null) return; |
| 58 | + if (person.isAlive) names.add(person.name); |
| 59 | + for (Person child : person.children) { |
| 60 | + getInheritanceOrder(child, names); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments