Javascript中的递归树插入

时间:2017-06-15 08:44:33

标签: javascript node.js recursion tree

我尝试使用tree-node在javascript中递归地将insert插入到树数据结构中,但是没有让它工作。 所以我的问题是如何处理这个问题。

这是我的数据:

[ { 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)

2 个答案:

答案 0 :(得分:1)

You could use a hash table for the last inserted nodes and keep the reference to the last nodes by overwriting the referenc.

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; }

答案 1 :(得分:0)

您的数据结构错误。 每个叶子'应该包含对“左”的引用。并且'对'元件。 例如:

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

儿童方法更适合图表。 但你仍然需要存储引用,而不是ID。