title: How to collect all nodes of a Tree structure, grouped by depth level?
body: <p>I have a classic Tree-structure with childs and parent node. Now, i would like to collect all nodes grouped by depth starting from the lowest level (i.e. in reverse order), like this:</p>
  
  <pre><code>nodes[
    ["A4"],
    ["A3","B3"],
    ["A2","B2","C2"],
    ["A1","B1","C1"],
    ["ROOT"]
  ];
  </code></pre>
  
  <p>While getting the depth level by using the recursive traversal approach is very easy, i'm wonder if there is any method to get immediately the depth level during the Tree traversal in a BFS or DFS search.</p>
  
  <p>I'am aware that i could store the depth level during the node insertion, but as i'm doing a lot of insertion and removals, i would prefer to collect the whole structure grouped by level just in one shot.</p>
  
  <p>Also, i haven't any preference to use BDS or DFS at all, both are just fine. Here is my actual code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>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 &gt; 0) {
      n = stack.pop();
      if(n.children.length == 0) {
        if(leafCallback) leafCallback(n, this);
         continue;
      }
      for(var i=n.children.length-1; i&gt;=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");</code></pre>
  </div>
  </div>
  </p>