Javascript 中的通用树实现

wh0*_*wh0 6 javascript tree

有没有人知道 JavaScript 的通用树(节点可能有多个子节点)实现?

至少应该可以做这些事情,

  1. 获取父节点。
  2. 获取子节点。
  3. 得到所有的后代。
  4. 删除所有后代。
  5. 删除子节点。

一些类似于邻接列表模型的实现。

背景:我需要为我的网页存储基于 JavaScript 的分层数据我找不到通用树的良好 JavaScript 实现,所以我所做的是使用 ajax 使用邻接列表模型和 php 将分层数据存储到数据库中。当用户在同一个浏览器的两个选项卡中打开同一个页面或在两个不同的浏览器中打开页面时,问题就出现了,因为这两个实例都在从同一个表中写入同一个表,这给我带来了任何可能的解决方法回答我的问题。

编辑: 性能在任何时候都不是我的限制,我不会有超过 50 个条目。

Kar*_*rol 9

你可以试试这个:https : //github.com/afiore/arboreal

或者这个:https : //github.com/mauriciosantos/buckets/(只有二叉搜索树,还有其他数据结构)

如果您需要更复杂的东西,您将需要编写自己的库(或至少一个具有您所描述的所有方法的对象)。

编辑:

这是我实现树功能的简单代码。删除所有后代并删除所有子项实际上是相同的......所以:

function Node(value) {

    this.value = value;
    this.children = [];
    this.parent = null;

    this.setParentNode = function(node) {
        this.parent = node;
    }

    this.getParentNode = function() {
        return this.parent;
    }

    this.addChild = function(node) {
        node.setParentNode(this);
        this.children[this.children.length] = node;
    }

    this.getChildren = function() {
        return this.children;
    }

    this.removeChildren = function() {
        this.children = [];
    }
}

var root = new Node('root');
root.addChild(new Node('child 0'));
root.addChild(new Node('child 1'));
var children = root.getChildren();
for(var i = 0; i < children.length; i++) {
    for(var j = 0; j < 5; j++) {
        children[i].addChild(new Node('second level child ' + j));
    }
}
console.log(root);
children[0].removeChildren();
console.log(root);
console.log(root.getParentNode());
console.log(children[1].getParentNode());
Run Code Online (Sandbox Code Playgroud)

在 Chrome(或其他支持控制台的浏览器)中运行它。

  • 干得好。在上面的例子中,一个让添加子节点变得容易的快速小改动是在 addChild() 方法中添加 return。返回 this.children[this.children.length -1]; (2认同)