Created
August 20, 2019 13:47
-
-
Save mvlootman/b2b31ee24fa4379064131b76f306e9b5 to your computer and use it in GitHub Desktop.
tree - go code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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