mat*_*cka 4 javascript tree data-structures
我在javascript中查找了这个基本格式的树结构:
function Tree(parent, child, data) {
this.parent = parent;
this.children = child || [];
this.data = data;
this.addNode ...
this.addChild ...
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是制作一棵"长"的树.我正在使用的数据是一条路径上的街道列表,这条路径几乎是一条直线路径,但是在路径中有一些小的分裂,数据看起来像:
A ->
B ->
C ->
D -> E,F
E ->
G ->
H
F -> I
I -> J
J -> K,L
K ->
M ->
N
L -> O
O -> P
Run Code Online (Sandbox Code Playgroud)
我想避免看起来像这样的代码:
tree.children[0].children[0].children[0].addNode("E");
tree.children[0].children[0].children[0].push("F");
Run Code Online (Sandbox Code Playgroud)
所以我的一个问题是如何遍历树,简单地说?
node = tree;
while(node.children != null)
node = node.children[0];
Run Code Online (Sandbox Code Playgroud)
如果你可以帮助我,我会很感激,谢谢,
mathacka
这种结构最可管理的方法是恕我直言,使用链表.
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;
}
Run Code Online (Sandbox Code Playgroud)
要遍历孩子,请执行以下操作:
function GetChildren(node)
{
var result=new Array();
var child=node.FirstChild;
while(child)
{
result.push(child);
child=child.NextSibling;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
(编辑)"节点" - 对象只是一个例子,它应该添加有意义的属性.使用它作为树中所有对象的基础,它可以具有任何深度而不会使其更复杂.您可以添加更多功能,如GetChildByName,RemoveChild等.