2018-12-11 01:23:18 +00:00
|
|
|
package day08
|
|
|
|
|
|
|
|
type Node struct {
|
|
|
|
Children []*Node
|
|
|
|
Metadata []int
|
|
|
|
}
|
|
|
|
|
2018-12-11 02:15:33 +00:00
|
|
|
func (node Node) SumMetadata() int {
|
|
|
|
sum := 0
|
|
|
|
for _, v := range node.Metadata {
|
|
|
|
sum += v
|
|
|
|
}
|
|
|
|
return sum
|
|
|
|
}
|
|
|
|
|
2018-12-11 01:23:18 +00:00
|
|
|
func BuildTree(data []int) *Node {
|
|
|
|
root, _ := buildTreeR(data, 0)
|
|
|
|
return root
|
|
|
|
}
|
|
|
|
|
|
|
|
func buildTreeR(data []int, index int) (*Node, int) {
|
|
|
|
node := &Node{}
|
|
|
|
numChildren := data[index]
|
|
|
|
numMetadata := data[index+1]
|
|
|
|
index += 2
|
|
|
|
|
|
|
|
for i := 0; i < numChildren; i++ {
|
|
|
|
var child *Node
|
|
|
|
child, index = buildTreeR(data, index)
|
|
|
|
node.Children = append(node.Children, child)
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := 0; i < numMetadata; i++ {
|
|
|
|
node.Metadata = append(node.Metadata, data[index+i])
|
|
|
|
}
|
|
|
|
|
|
|
|
return node, index + numMetadata
|
|
|
|
}
|