javascript - 我需要使用 JavaScript 创建自定义树数据结构

标签 javascript data-structures tree

我在 javascript 中查找了树结构的基本格式:

function Tree(parent, child, data) {
    this.parent = parent;
    this.children = child || [];
    this.data = data;
    this.addNode ...
    this.addChild ...
}

我遇到的问题是制作一棵“长”的树。我使用的数据是一条小径上的街道列表,几乎是一条直线路径,但小径上有几个小裂缝,数据看起来像这样:

A -> 
B -> 
C -> 
D -> E,F   
E -> 
G -> 
H    
F -> I  
I -> J  
J -> K,L   
K ->
M -> 
N
L -> O
O -> P

我想避免这样的代码:

tree.children[0].children[0].children[0].addNode("E");
tree.children[0].children[0].children[0].push("F");

所以我的一个问题是如何简单地通过语句来遍历树?

node = tree;
while(node.children != null)
    node = node.children[0];

如果你能帮助我,我将不胜感激,谢谢,

数学题

最佳答案

对于这种结构,最易于管理的方法是恕我直言,使用链表。

function Node(parentNode)
{
    this.Parent=parentNode;
    this.FirstChild=null;
    this.LastChild=null;
    this.PreviousSibling=null;
    this.NextSibling=null;
}
Node.prototype.AddChild=function(child)
{
    child.Parent = this;
    child.PreviousSibling = this.LastChild;
    if (this.LastChild != null)
        this.LastChild.NextSibling = child;
    this.LastChild = child;
    if (this.FirstChild == null)
        this.FirstChild = child;
}

要遍历 child ,做这样的事情:

function GetChildren(node)
{
    var result=new Array();
    var child=node.FirstChild;
    while(child)
    {
        result.push(child);
        child=child.NextSibling;
    }
    return result;
}

(编辑)“节点”对象只是一个例子,它应该添加有意义的属性。使用它作为树中所有对象的基础,它可以有任何深度而不会使它更复杂。您可以添加更多函数,例如 GetChildByName、RemoveChild 等。

关于javascript - 我需要使用 JavaScript 创建自定义树数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17750650/

相关文章:

javascript - XMLHttpRequest - 发送文件?

algorithm - 在没有单独函数的情况下实现递归

c++ - 这个问题有更好的数据结构和算法选择吗?

data-structures - 实践中哪个优先级队列更快?

Python树遍历和排序列表中的项目组排序

r - 根据父/子/兄弟关系从树中修剪/检索节点

javascript - 删除树节点但保留其子节点的方法的名称

php - 如何将 PHP 变量传递给 javascript?

javascript - 如何计算 HTML 元素内容的可见高度和宽度?

javascript - 如何获取元素的内容(包括监听器)