【发布时间】:2017-06-15 08:44:33
【问题描述】:
我尝试使用树节点在 javascript 中递归地将插入写入树数据结构,但没有让它工作。 所以我的问题是,如何解决这个问题。
这是我的数据:
[ { id: 'a', children: [ 'b', 'c' ] },
{ id: 'b', children: [ '' ] },
{ id: 'c', children: [ 'b', 'd' ] },
{ id: 'd', children: [ 'b' ] } ]
我希望它显示在树中,如下所示:
a
/\
b c
/\
b d
\
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)
【问题讨论】:
-
你真的有两次节点
b吗?它会生成一个循环引用。 -
是的,至少 3 次,但它不会创建一个循环,因为 b 没有指向它的调用者之一。
-
如何分离节点?还是您从头开始使用严格的顺序并仅使用最后相同的命名节点?
-
那可能是副本。它不能是同一个节点,只能是值。
-
为什么
''没有给孩子?
标签: javascript node.js recursion tree