dongzhashou0116 2019-07-10 16:06
浏览 38

无法创建结构正确的树

I have a struct with the following structure

type Node struct {
    Id string,
    Type string,
    Children []*Node
}

My input is of the following format

[60566 605 6061],
[60566 605 6065],
[60653 606 6109]]
package main
import (
    "fmt"
)

type Node struct {
    Id       string
    Type     string
    Children []*Node
}

func buildFullNode(values []string) Node {
    bottomNode := Node{
        Id:   values[2],
        Type: "TYPE3",
    }
    middleNode := Node{
        Id:       values[1],
        Type:     "TYPE2",
        Children: []*Node{&bottomNode},
    }
    rootNode := Node{
        Id:       values[0],
        Type:     "TYPE1",
        Children: []*Node{&middleNode},
    }
    return rootNode
}

func newNode(id string, providerType string) Node {
    return Node{
        Id: id,
        Type: providerType,
    }
}

func insertNode(nodes []string, node *Node, types []string, count uint64) *Node {

    if uint64(len(types)) == count {
        return node
    }
    if node.Id == nodes[0] {
        count++
        return insertNode(nodes[1:], node,  types, count)
    } else {
        newNode := newNode(nodes[0], types[count])
        node.Children = append(node.Children, &newNode)
        count++
        return insertNode(nodes[1:], node, types, count)
    }
}

func buildNode(values []string, node []*Node) *Node {
    if len(node) == 0 {
        rootNode := buildFullNode(values)
        node = append(node, &rootNode)
        return node[len(node)-1]
    } else {
        var types = []string{
            "TYPE1", "TYPE2", "TYPE3",
        }
        newNode := insertNode(values, node[len(node)-1], types, 0)
        return newNode
    }
}

func main() {
    rootNode := Node{
        Id: "",
    }

    var nestedSlice = [][]string{
        {"60566", "605", "6056"},
        {"60566", "605", "6061"},
        {"60566", "605", "6065"},
        {"60653", "606", "6109"},
    }

    for _, value := range nestedSlice {
        node := buildNode(value, rootNode.Children)
        fmt.Println(node)
    }
}

In the end I should have the following tree structure

           nil
        /      \
     60566    60653
       |        |
      605      606
      /\       |
   6056 6056  6109

I think the problem is that in the first if in insertNode statement I am not returning the full struct but rather the last updated one. Also I am not sure on how to append correctly to the root of the rootNode

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
    • ¥15 求解 yolo算法问题
    • ¥15 虚拟机打包apk出现错误
    • ¥15 用visual studi code完成html页面
    • ¥15 聚类分析或者python进行数据分析
    • ¥15 三菱伺服电机按启动按钮有使能但不动作
    • ¥15 js,页面2返回页面1时定位进入的设备
    • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
    • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
    • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝