douer9399 2012-12-01 21:01
浏览 26
已采纳

将节点添加到树

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条回答 默认 最新

  • doufeikuang7724 2012-12-02 00:00
    关注

    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
    ", &node1, node1)
        fmt.Printf("node2: %p %v
    ", &node2, node2)
        fmt.Printf("node3: %p %v
    ", &node3, node3)
        fmt.Printf("node4: %p %v
    ", &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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计