无法创建结构正确的树

时间:2019-07-10 16:06:57

标签: algorithm go tree

我有一个具有以下结构的结构

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

我的输入格式如下

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

最后,我应该具有以下树结构

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

我认为问题在于,在第一个if in insertNode语句中,我没有返回完整的结构,而是最后一个更新的结构。我也不确定如何正确附加到rootNode的根

0 个答案:

没有答案