如何在golang中合并两棵树?

时间:2016-03-18 04:21:47

标签: go tree

树结构如下:

 type TreeData struct {
    Name          string      `json:"name"`
    Depth         int         `json:"depth"`
    Children      []TreeData  `json:"children"`
}

我有两棵树,我想将它们合并到一棵树上。 我怎么能这样做?
如果有人能告诉我你的代码,我将非常感谢!!
我想知道我是否可以使用递归方式来完成合并?

treeone:

{
     "name": ".",
     "depth": 1,
     "children": [
         {
             "name": "com",
             "depth": 2,
             "children": [
                 {
                     "name": "didi"
                     "depth": 3,
                     "children": [
                         {
                             "name": "dev",
                             "depth": 4,
                             "children": null
                         }
                     ]
                 }
             ]
         }
     ]
}

treetwo:

{
     "name": ".",
     "depth": 1,
     "children": [
         {
             "name": "com",
             "depth": 2,
             "children": [
                 {
                     "name": "didi"
                     "depth": 3,
                     "children": [
                         {
                             "name": "influxdb",
                             "depth": 4,
                             "children": [
                                 {
                                     "name": "cluster-one"
                                     "depth": 5
                                     "children": null
                                 }
                             ]    
                         } 
                     ]
                 }
             ]
         }
     ]
}

合并:

{
     "name": ".",
     "depth": 1,
     "children": [
         {
             "name": "com",
             "depth": 2,
             "children": [
                 {
                     "name": "didi"
                     "depth": 3,
                     "children": [
                         {
                             "name": "influxdb",
                             "depth": 4,
                             "children": [
                                 {
                                     "name": "cluster-one"
                                     "depth": 5
                                     "children": null
                                 }
                             ]
                         },
                         {
                            "name": "dev",
                            "depth": 4,
                            "children": null
                         }
                     ]
                 }
             ]
         }
     ]
}

1 个答案:

答案 0 :(得分:0)

我找到一个很好的解决方案golang创建一个树! http://blog.csdn.net/xtxy/article/details/50812392