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
| type ThroneInheritance struct { Root *Node Deads map[string]*Node }
type Node struct { Name string IsDead bool Children *[]*Node }
func Constructor(kingName string) ThroneInheritance { root := &Node{ Name: kingName, Children: &[]*Node{}, } return ThroneInheritance{ Root: root, Deads: map[string]*Node{ kingName: root, }, } }
func (this *ThroneInheritance) Birth(parentName string, childName string) { node := &Node{ Name: childName, Children: &[]*Node{}, } children := this.Deads[parentName].Children *children = append(*children, node) this.Deads[childName] = node }
func (this *ThroneInheritance) Death(name string) { this.Deads[name].IsDead = true }
func (this *ThroneInheritance) GetInheritanceOrder() []string { ans := []string{} var dfs func(root *Node) dfs = func(root *Node) { if root == nil { return } if !root.IsDead { ans = append(ans, root.Name) } for _, child := range *root.Children { dfs(child) } } dfs(this.Root) return ans }
|