我有一个带childs和父节点的经典Tree结构。现在,我想收集的最低水平(即以相反的顺序)开始通过深度分组的所有节点,就像这样:如何收集树结构的所有节点,按深度级别分组?
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
@ guest271314:抱歉没有 - 当然,这是它的根的路径长度 – deblocker