将二进制树编码为Json

时间:2014-04-30 02:56:10

标签: php json binary-tree

我在我的数据库中存储了一堆数据,以在html画布中绘制二叉树


Idx /姓名

1 Apple

2蜜蜂

3 Cafe

4钻石

8 East

9游戏

16爱好


这里,idx表示二叉树中项目的位置。所以上面的数据在树中看起来像这样


               1.Apple
               /     \
            2.Bee    3.Cafe
             /
      4.Diamond
       /      \
  8.East    9.Game
     /
16.Hobby

现在,我需要将数据库行编码为json格式:

{
    id: "1",
    name: "Apple",
    data: {},
    children: [{
                   id: "2",
                   name: "Bee",
                   data: {},
                   children: [{
                       id: "4",
                       name: "Diamond",
                       data: {},
                       children: [{
                         // East/Game/Hobby comes here in the same manner...
                       }]
                   }]
               },
               {
                   id: "3",
                   name: "Cafe",
                   data: {},
                   children: [] // has no children
               }]
}

我尝试过的是创建一个数组数组,然后通过抓取一个值并将其放入其父数组并从数组中删除它来按顺序浏览所有值。所以,我的伪代码是这样的......

nodeArray = [1,2,3,4,8,9,16];  <-each node is an object with needed data contained.
treeArray = [........]  <- arrays with key=>each index / value=>empty
while(nodeArray size is larger than 1) // 1 = the top most value 
{
    grab the last node from nodeArray
    parent_idx = (int)(last one id / 2)
    push the last node into the treeArray[parent_idx]
    pop the used index
}

Then, I will have treeArray something like this

treeArray = [
  1:[2,3]
  2:[4]
  4:[8,9]
  8:[16]
]

...这不是我正在寻找的数组转换二进制树。

所以,我需要按照desc顺序浏览treeArray并重新定位它们......是的。我知道我在这里搞砸了:(它变得越来越复杂,越来越难理解。

会有更优雅,更简单的方法吗? :(

1 个答案:

答案 0 :(得分:1)

我最终使用javascript并循环遍历每个节点并调用以下函数

var objlist = {};
function buildTree(id, parent_id, data)
{
   if(id in objlist) alert("It already exists!");
   objlist[id] = { id: id, data: data, children: [] };
   if (parent_id in objlist)
   {
      objlist[parent_id].children.push(objlist[id]);
   }
}

其中parent_id是id / 2。