title: Variables not closing
body: <p>I am trying to do a depth-first search (DFS) of a generic tree. The goal for each node is to know its level AND the maximum number of levels beneath it.  An example tree looks like:</p>
  
  <p><a href="https://i.stack.imgur.com/GEBek.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GEBek.png" alt="enter image description here"></a></p>
  
  <p>The DFS order should (I think) be: 1,2,3,5,6,7,4,8,9,10,11.</p>
  
  <p>What I am trying to achieve is:
  Node 1: Level 1, max levels beneath=4</p>
  
  <p>Node 2: Level 2, max levels beneath=3</p>
  
  <p>Node 3: Level 3, max levels beneath=2</p>
  
  <p>...</p>
  
  <p>Node 9: Level 2, max levels beneath=1</p>
  
  <p>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.</p>
  
  <pre><code> 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&gt;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");
  </code></pre>