【问题标题】:Recursive Tree insertion in JavascriptJavascript中的递归树插入
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 你已经将函数中的数据作为数组传递,但没有在任何地方使用数组并直接改变数据,为什么?
【解决方案2】:

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

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

儿童方法更适合图表。 但是您仍然必须存储引用,而不是 id。

【讨论】:

  • 但左/右仅适用于二叉树,不是吗?在我的情况下,我可以有两个以上的孩子,所以我不能使用左右。
  • 是的,你是对的。是我的小姐。我仍然会存储引用,而不是 ID。
猜你喜欢
  • 2015-09-19
  • 2012-11-16
  • 2014-12-03
  • 2017-01-01
  • 2020-07-24
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多