算法:
方法一:hash table
type ThroneInheritance struct {
King string
PeopleAlive map[string]bool
PeopleChild map[string][]string
}
func Constructor(kingName string) ThroneInheritance {
t := ThroneInheritance{
King: kingName,
PeopleAlive: make(map[string]bool, 0),
PeopleChild: make(map[string][]string, 0),
}
t.PeopleAlive[kingName] = true
return t
}
func (this *ThroneInheritance) Birth(parentName string, childName string) {
if this.PeopleChild[parentName] == nil {
this.PeopleChild[parentName] = make([]string, 0)
}
this.PeopleChild[parentName] = append(this.PeopleChild[parentName] , childName)
this.PeopleAlive[childName] = true
}
func (this *ThroneInheritance) Death(name string) {
this.PeopleAlive[name] = false
}
func (this *ThroneInheritance) GetInheritanceOrder() []string {
order := make([]string, 0)
var successor func(x string)
successor = func(x string) {
if this.PeopleAlive[x] {
order = append(order, x)
}
if this.PeopleChild[x] == nil {
// 没有儿子了
return
}
for _, child := range this.PeopleChild[x] {
successor(child)
}
}
successor(this.King)
return order
}
/**
* Your ThroneInheritance object will be instantiated and called as such:
* obj := Constructor(kingName);
* obj.Birth(parentName,childName);
* obj.Death(name);
* param_3 := obj.GetInheritanceOrder();
*/