将二叉树编码为 Json

Rac*_*oon 5 php json binary-tree

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


身份证号/名称

1 个苹果

2 蜜蜂

3 咖啡厅

4 钻石

8 东

9 游戏

16 爱好


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


               1.Apple
               /     \
            2.Bee    3.Cafe
             /
      4.Diamond
       /      \
  8.East    9.Game
     /
16.Hobby
Run Code Online (Sandbox Code Playgroud)

现在,我需要将数据库行编码为 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
               }]
}
Run Code Online (Sandbox Code Playgroud)

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

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]
]
Run Code Online (Sandbox Code Playgroud)

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

所以,我需要按降序顺序遍历 treeArray 并重新定位它们......是的。我知道我在这里搞砸了:(它变得更加复杂和难以理解。

有没有更优雅、更简单的方法来做到这一点?:(

Rac*_*oon 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]);
   }
}
Run Code Online (Sandbox Code Playgroud)

其中parent_id 是id/2。