向树中添加节点

huangapple go评论89阅读模式
英文:

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 [] []}

Slice types

Appending to and copying slices

SliceTricks

Pointer types

huangapple
  • 本文由 发表于 2012年12月2日 05:01:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/13663703.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定