2 回答

TA貢獻1828條經驗 獲得超3個贊
更簡單的方法
我們也可以說這是更簡潔的方法,用構造函數語法構造節點。
type Node struct {
Name string
Children []*Node
}
func first_example() {
root := Node{
Name: "1",
Children: []*Node{
{
Name: "3",
Children: []*Node{
{
Name: "5",
},
},
},
},
}
bytes, err := json.Marshal(root)
if err != nil {
panic(err)
}
fmt.Println(string(bytes))
}
更難的方法
輸出是相同的,但它更加動態,并允許您存儲其他值,另一方面,遍歷樹更煩人,因為您必須始終投射所有內容。
func second_example() {
root := map[string]interface{}{
"Name": "1",
"Children": []map[string]interface{}{
{
"Name": "3",
"Children": []map[string]interface{}{
{
"Name": "5",
},
},
},
},
}
bytes, err := json.Marshal(root)
if err != nil {
panic(err)
}
fmt.Println(string(bytes))
}
輸出
{"Name":"1","Children":[{"Name":"3","Children":[{"Name":"5","Children":null}]}]} // #1
{"Children":[{"Children":[{"Name":"5"}],"Name":"3"}],"Name":"1"} // #2
編輯
此外,這里還有向結構中插入節點的函數。如果操作失敗,則返回 False。
func (n *Node) InsertNode(path string, o *Node) bool {
parts := strings.Split(path, " ")
target := n
for _, part := range parts {
found := false
for _, child := range target.Children {
if child.Name == part {
target = child
found = true
break
}
}
if !found {
return false
}
}
target.Children = append(target.Children, o)
return true
}
func third_example() {
root := &Node{Name: "1"}
root.Children = append(root.Children, &Node{Name: "3"})
root.InsertNode("3", &Node{Name: "5"})
bytes, err := json.Marshal(root)
if err != nil {
panic(err)
}
fmt.Println(string(bytes))
}

TA貢獻1801條經驗 獲得超16個贊
首先用方法定義一個類型 -NodeAddChild()
type Node struct {
Fn string `json:"Funcname"`
Children []*Node `json:"Nodes"`
}
func (node *Node) AddChild(child *Node) {
node.Children = append(node.Children, child)
}
一個構造函數,用于為給定構造一個新節點fn -
func CreateNewNode(fn string) *Node {
newNode := new(Node)
newNode.Fn = fn
return newNode
}
要從映射生成樹定義函數,如下所示 -MakeTreeFromMap()
// MakeTreeFromMap generates a tree from given map and returns pointer to root node of tree.
func MakeTreeFromMap(treeMap map[string][]string, rootNodeFn string) *Node {
cache := make(map[string]*Node)
for fn, children := range treeMap {
if _, nodeExists := cache[fn]; !nodeExists {
node := CreateNewNode(fn)
cache[fn] = node
}
for _, childFn := range children {
if _, childExists := cache[childFn]; !childExists {
child := CreateNewNode(childFn)
cache[childFn] = child
}
cache[fn].AddChild(cache[childFn])
}
}
return cache[rootNodeFn]
}
將樹序列化為 JSON -
root_node := MakeTreeFromMap(m, "root_node")
bytes, err := json.Marshal(root_node)
if err != nil {
log.Fatal(err)
}
- 2 回答
- 0 關注
- 130 瀏覽
添加回答
舉報