Skip to content

Instantly share code, notes, and snippets.

@mvlootman
Created August 20, 2019 13:47
Show Gist options
  • Save mvlootman/b2b31ee24fa4379064131b76f306e9b5 to your computer and use it in GitHub Desktop.
Save mvlootman/b2b31ee24fa4379064131b76f306e9b5 to your computer and use it in GitHub Desktop.
tree - go code
package tree
import (
"fmt"
"sort"
)
//Record sctruct holds initial records
type Record struct {
ID int
Parent int
}
//Node represents a tree node
type Node struct {
ID int
Children []*Node
}
//Build creates tree from given list of records
func Build(records []Record) (*Node, error) {
nodes := make([]Node, len(records))
if len(records) == 0 {
return nil, nil
}
sort.Slice(records, func(i, j int) bool { return records[i].ID < records[j].ID })
for _, n := range records {
if n.ID != 0 {
nodes[n.Parent].Children = append(nodes[n.Parent].Children, &nodes[n.ID])
}
nodes[n.ID].ID = n.ID
}
return &nodes[0], nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment