簡體   English   中英

Javascript中的遞歸樹插入

[英]Recursive Tree insertion in Javascript

我嘗試使用樹節點在 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)

您可以對最后插入的節點使用哈希表,並通過覆蓋引用來保留對最后一個節點的引用。

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

你的數據結構是錯誤的。 每個“葉子”都應該包含對“左”和“右”元素的引用。 例如:

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

兒童方法更適合圖。 但是您仍然必須存儲引用,而不是 id。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM