英文:
Adding nodes to a tree
问题
我正在使用Go编程语言开发一个项目,需要使用树结构并能够向树中添加节点(很多节点)。每个节点都是以下结构的结构体:
type Node struct {
ip net.IP
nodes []Node
value int
}
每个节点可以有不同数量的子节点(1-4个)。一个IP地址(我稍后会搜索)可以包含在节点中,但大多数节点的该元素将为nil。
我可以很容易地在其他语言中实现这个功能,但我需要找到一种在Go中高效地向树中添加这些节点的方法。
英文:
I'm working on a project in the Go programming language where I need a tree structure and the ability to add nodes (alot of them) to the tree. Each node is a struct like the following:
type Node struct {
ip net.IP
nodes []Node
value int
}
The number of nodes each node can have is variable (between 1-4). An IP address (I'll searching for late) can be contained at the node, but most nodes will be nil for that element.
I can easily do this in other langues, but I need to find an efficient way of adding these nodes to a tree in Go.
答案1
得分: 2
例如,使用nodes
作为指向Node
的切片,
package main
import (
"fmt"
"net"
)
type Node struct {
value int
ip net.IP
nodes []*Node
}
func main() {
node1 := Node{value: 1}
node2 := Node{value: 2}
node3 := Node{value: 3}
node4 := Node{value: 4}
node1.nodes = append(node1.nodes, &node2, &node3)
node2.nodes = append(node2.nodes, &node4)
node3.nodes = append(node3.nodes, &node4)
fmt.Printf("node1: %p %v\n", &node1, node1)
fmt.Printf("node2: %p %v\n", &node2, node2)
fmt.Printf("node3: %p %v\n", &node3, node3)
fmt.Printf("node4: %p %v\n", &node4, node4)
}
输出:
node1: 0xc200069100 {1 [] [0xc200069180 0xc200069200]}
node2: 0xc200069180 {2 [] [0xc200069240]}
node3: 0xc200069200 {3 [] [0xc200069240]}
node4: 0xc200069240 {4 [] []}
英文:
For example, with nodes
as a slice of pointers to Node
,
package main
import (
"fmt"
"net"
)
type Node struct {
value int
ip net.IP
nodes []*Node
}
func main() {
node1 := Node{value: 1}
node2 := Node{value: 2}
node3 := Node{value: 3}
node4 := Node{value: 4}
node1.nodes = append(node1.nodes, &node2, &node3)
node2.nodes = append(node2.nodes, &node4)
node3.nodes = append(node3.nodes, &node4)
fmt.Printf("node1: %p %v\n", &node1, node1)
fmt.Printf("node2: %p %v\n", &node2, node2)
fmt.Printf("node3: %p %v\n", &node3, node3)
fmt.Printf("node4: %p %v\n", &node4, node4)
}
Output:
node1: 0xc200069100 {1 [] [0xc200069180 0xc200069200]}
node2: 0xc200069180 {2 [] [0xc200069240]}
node3: 0xc200069200 {3 [] [0xc200069240]}
node4: 0xc200069240 {4 [] []}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论