递归创建嵌套结构

I have a struct of the following format

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

Input

I have the following input

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

The code

package main

import (
    //"fmt"
    "github.com/davecgh/go-spew/spew"
)

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

func createNode(values []string, node *Node) *Node {

}

func insert(values []string, nodes []*Node) []*Node {
    if len(nodes) == 0 {
        rootNode := createNode(values, &Node{})
        nodes = append(nodes, rootNode)
        return nodes
    } else {
        for _, node := range nodes {
            if node.Id == values[0] {
                return insert(values[1:], node.Children)
            }
        }
        anotherRoot := &Node{
            Id: values[0],
        }
        nodes = append(nodes, anotherRoot)
    }
    return nodes
}

func main() {
    nodes := make([]*Node, 0, 6)

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

    for _, value := range nestedSlice {
        nodes = insert(value, nodes)
    }

    spew.Dump(nodes)
}

I am having troubles with createNode function. I am not sure how can I take the slice and create it using recursion

I want to be able to have the following struct in the end

[{
    Id: 60566,
    Children: [{
        Id: 605,
        Children: [{
            Id: 6056
        }, {
            Id: 6061
        }, {
            Id: 6065
        }]
    }, {
        Id: 603,
        Children: [{
            Id: 6065
        }]
    }]
}, {
    Id: 60653
    Children: [{
        Id: 606,
        Children: [{
            Id: 6109
        }]
    }]
}]




1个回答

This would be my approach, I'll create the Node and then add a separate method to add children.

func createNode(id string) *Node{
   return &Node{
      id: id,
      children: make([]*Node, 0)
   }
}

And now add the nodes.

func(n *Node) addChildren(nodes []*Node){
   for _, node := range nodes{
     n.children.append(node)
   }
}

But then if you wish to, you could combine the two.

func createNode(id string, nodes []*Node) *Node{
   p= Node{
      id: id,
      children: make([]*Node, 0)
   }
   for _, node := range nodes{
     p.children.append(node)
   }
   return &p
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐