在Javascript中recursion树插入

我试着用树节点在JavaScript中recursion地将插入写入到树型数据结构中,但是不要使它工作。 所以我的问题是,如何处理这个问题。

这是我的数据:

[ { id: 'a', children: [ 'b', 'c' ] }, { id: 'b', children: [ '' ] }, { id: 'c', children: [ 'b', 'd' ] }, { id: 'd', children: [ 'b' ] } ] 

我想让它出现在如下的树中:

  a /\ bc /\ bd \ b 

编辑:添加代码

我以为我可以做这样的事情,但这是行不通的,当然因为嵌套的forEach有很高的复杂性:

 var Node = require("tree-node"); var testarray = [ { id: 'a', children: [ 'b', 'c' ] }, { id: 'b', children: [ '' ] }, { id: 'c', children: [ 'b', 'd' ] }, { id: 'd', children: [ 'b' ] } ] function appendChildRecursive(parent) { var childnode = new Node() var data = parent.data("children") testarray.forEach(function(item){ if(data !== undefined) { data.forEach(function (child) { if (item.id == child) { childnode.data("id", child).data("children", item.children) childnode = appendChildRecursive(childnode) parent.appendChild(childnode) } }) } }) return parent } var root = new Node(); root.data("id",testarray[0].id).data("children",testarray[0].children) root=appendChildRecursive(root) 

你可以为最后插入的节点使用一个散列表,并通过覆盖引用来保持对最后节点的引用。

 var data = [{ id: 'a', children: ['b', 'c'] }, { id: 'b', children: [] }, { id: 'c', children: ['b', 'd'] }, { id: 'd', children: ['b'] }], tree = function (array) { var nodes = Object.create(null), r = {}; data.forEach(function (a) { if (!nodes[a.id]) { nodes[a.id] = { id: a.id, children: [] }; r = nodes[a.id]; } a.children.forEach(function (b) { nodes[b] = { id: b, children: [] }; nodes[a.id].children.push(nodes[b]); }); }); return r; }(data); console.log(tree); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

你的数据结构是错误的。 每个“叶子”应该包含对“左”和“右”元素的引用。 例如:

 const first = { id: 'a', left: null, right: null }; const second = { id: 'b', left: null, right: first }; // etc... 

孩子的方法会更适合graphics。 但是你仍然需要存储引用,而不是IDS。