我在 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/