【发布时间】:2017-09-24 08:33:03
【问题描述】:
我有一个带有子节点和父节点的经典树结构。现在,我想收集从最低级别开始按深度分组的所有节点(即以相反的顺序),如下所示:
nodes[
["A4"],
["A3","B3"],
["A2","B2","C2"],
["A1","B1","C1"],
["ROOT"]
];
虽然使用递归遍历方法获得深度级别非常容易,但我想知道是否有任何方法可以在 BFS 或 DFS 搜索中的树遍历期间立即获得深度级别。
我知道我可以在节点插入期间存储深度级别,但由于我正在执行大量插入和删除操作,我更愿意一次性收集按级别分组的整个结构。
另外,我根本不喜欢使用 BDS 或 DFS,两者都很好。这是我的实际代码:
function Node(code, parent) {
this.code = code;
this.children = [];
this.parentNode = parent;
}
Node.prototype.addNode = function (code) {
var l = this.children.push(new Node(code, this));
return this.children[l-1];
};
Node.prototype.dfs = function (leafCallback) {
var stack=[this], n, depth = 0;
while(stack.length > 0) {
n = stack.pop();
if(n.children.length == 0) {
if(leafCallback) leafCallback(n, this);
continue;
}
for(var i=n.children.length-1; i>=0; i--) {
stack.push(n.children[i]);
}
depth++; // ???
}
};
var tree = new Node("ROOT");
tree.addNode("A1").addNode("A2").addNode("A3").addNode("A4");
tree.addNode("B1").addNode("B2").addNode("B3");
tree.addNode("C1").addNode("C2");
【问题讨论】:
-
depth是否引用了.length的.children数组? -
@guest271314: 抱歉不——当然,这是到其根目录的路径长度
标签: javascript tree depth-first-search breadth-first-search