I am trying to do a depth-first search (DFS) of a generic tree.
(我正在尝试对通用树进行深度优先搜索(DFS)。)
The goal for each node is to know its level AND the maximum number of levels beneath it. (每个节点的目标是知道其级别及其下的最大级别。)
An example tree looks like: (示例树如下所示:)
The DFS order should (I think) be: 1,2,3,5,6,7,4,8,9,10,11.
(DFS顺序应该是:1、2、3、5、6、7、4、8、9、10、11。)
What I am trying to achieve is: Node 1: Level 1, max levels beneath=4
(我正在尝试实现的是:节点1:级别1,最大级别低于= 4)
Node 2: Level 2, max levels beneath=3
(节点2:级别2,最大级别低于= 3)
Node 3: Level 3, max levels beneath=2
(节点3:级别3,最大级别低于= 2)
...
(...)
Node 9: Level 2, max levels beneath=1
(节点9:等级2,最大等级低于= 1)
I am, so far, able to properly count the levels and max levels, but whenever I try and save them to a new object, what ultimately results is the last level/max-level combination of numbers (in this example, it would be level=3, max-level beneath=0. I think it is not closing over the variables properly, but I must admit I can't figure out how to change it to make it work. I assume it must be some sort of closure, but I haven't been able to adapt the other Stack answers I've found on closures.
(到目前为止,我已经能够正确地计算级别和最大级别,但是每当我尝试将它们保存到新对象时,最终结果是数字的最后一个级别/最大级别组合(在本示例中,它将是级别= 3,最大级别低于=0。我认为它没有正确关闭变量,但我必须承认我不知道如何更改它以使其起作用,我认为它必须是某种形式的闭合,但是我无法适应在闭包上找到的其他Stack答案。)
var groupIDInfo={
BASE:[1], 1:[2,8,9], 2:[3,4], 3:[5], 4:[], 5:[6,7], 6:[], 7:[], 8:[],
9:[10,11], 10:[], 11:[]}
var levelInfo={};
var level=0;
var longestPath=0;
var levelAndPath=[];
function detLevels(groupIDInfo, parent){
if(!(parent in groupIDInfo)){
console.log("parent not in array");
return;
}
groupIDInfo[parent].forEach(function (child){
level++;
if (level>longestPath){
longestPath=level;
}
levelAndPath[0]=level;
levelAndPath[1]=longestPath;
levelInfo[child]=levelAndPath;
detLevels(groupIDInfo, child);
level--;
//set parent longest path
longestPath=level;
levelInfo[parent]=levelAndPath;
});
}
detLevels(groupIDInfo, "BASE");
ask by robert smith translate from so