package tree import "fmt" // debug // FindOrder determines the correct order according to these rules: // 1. A node cannot come before all of its parents have been included. // 2. At any given time, the lowest-lettered step must be executed. func FindOrder(root *Node) []*Node { seen := make(map[rune]bool) return findOrderR(root, seen) } func findOrderR(node *Node, seen map[rune]bool) []*Node { order := []*Node{} // debug fmt.Printf("In node: %c | Children: ", node.Name) for _, child := range node.Children { fmt.Printf("%c ", child.Name) } fmt.Printf("| Parents: ") for _, parent := range node.Parents { fmt.Printf("%c ", parent.Name) } fmt.Println() // end debug // add the node, but only if all its parents have been seen if len(node.Parents) == 0 { seen[node.Name] = true } else { for _, parent := range node.Parents { if _, ok := seen[parent.Name]; !ok { return order } } if _, ok := seen[node.Name]; !ok { order = append(order, node) fmt.Printf("Added node: %c\n", node.Name) seen[node.Name] = true } } // recurse for _, child := range node.Children { order = append(order, findOrderR(child, seen)...) } return order }