javascript - Javascript 中的递归树插入

标签 javascript node.js recursion tree

我尝试使用树 Node 在 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)

最佳答案

您可以对最后插入的 Node 使用哈希表,并通过覆盖引用来保留对最后 Node 的引用。

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 = {};
        array.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; }

关于javascript - Javascript 中的递归树插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44562842/

相关文章:

javascript - React 无状态示例

javascript - 如何在 IE11 中禁用平滑滚动

javascript - Typescript 生成带有 `#private;` 字段的声明 d.ts 文件

javascript - 在nodejs中将从文件读取的字符串转换为json对象

JavaScript - 存储页面重新加载的倒计时截止时间

node.js - 无法在使用带有 NodeJS 的 Handlebars 的 View 中查找 View "index"

node.js - npm、nodejs、package.json、模块版本不匹配。预期48,得到51

java - 当我们调用 function(2) 时,为什么这个函数返回 83 而不是 5?

php - 令人费解的 php 递归

javascript - 在递归函数调用中递增计数器