Advertisement
Guest User

Untitled

a guest
Dec 28th, 2018
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.16 KB | None | 0 0
  1. package tree
  2.  
  3. import (
  4.     "fmt"
  5.     "sort"
  6. )
  7.  
  8. const TestVersion = 2
  9.  
  10. type Record struct {
  11.     ID     int
  12.     Parent int
  13. }
  14.  
  15. type storage []Record
  16.  
  17. type Node struct {
  18.     ID       int
  19.     Children []*Node
  20. }
  21.  
  22. //Build function
  23. func Build(records []Record) (*Node, error) {
  24.     if len(records) <= 0 {
  25.         return nil, nil
  26.     }
  27.     sort.Sort(storage(records))
  28.     nodes := make([]*Node, len(records))
  29.     for r, rec := range records {
  30.         nodes[r] = &Node{ID: rec.ID}
  31.         if r == 0 && (rec.ID != 0 || rec.Parent != 0) {
  32.             return nil, fmt.Errorf("oops, smt went wrong %s", rec.String())
  33.         } else if r == 0 {
  34.             continue
  35.         } else if r != rec.ID || rec.ID <= rec.Parent {
  36.             return nil, fmt.Errorf("ooops smt went wrong: %s", rec.String())
  37.         }
  38.  
  39.         if parent := nodes[rec.Parent]; parent != nil {
  40.             parent.Children = append(parent.Children, nodes[r])
  41.         }
  42.     }
  43.  
  44.     return nodes[0], nil
  45. }
  46.  
  47. func (r *Record) String() string {
  48.     return fmt.Sprintf("(%d,%d)", r.ID, r.Parent)
  49. }
  50.  
  51. func (elem storage) Len() int           { return len(elem) }
  52. func (elem storage) Swap(j, k int)      { elem[j], elem[k] = elem[k], elem[j] }
  53. func (elem storage) Less(j, k int) bool { return elem[j].ID < elem[k].ID }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement