title: How to track the depth in this object graph depth-first search algorithm?
body: <p>I have this code which iterates over a tree, doing a depth-first search. Every element is tackled exactly once. Very good.</p>
  
  <pre><code>-(void)iterateOverTree:(TreeNode *)node
  {
      NSMutableArray * elements = [NSMutableArray array];
      [elements addObject:node];
  
      while([elements count])
      {
          TreeNode * current = [elements objectAtIndex:0];
          [self doStuffWithNode:current];
          for(TreeNode * child in current.children)
          {
              [elements addObject:child];
          }
  
          [elements removeLastObject];
      }
  }
  </code></pre>
  
  <p>BUT: How can I keep track of the current depth in the graph? I need to know the level of depth. So for example I have these nodes:</p>
  
  <p>A has childs B, J.
  B has child C.
  C has child D.
  D has childs E, F, I.</p>
  
  <p>When A is at depth level 1, then B is 2 and C is 3.</p>
  
  <p>With recursion it was very easy to keep track of the current depth level. Just inrement a variable before calling itself and decrement it after calling itself.</p>
  
  <p>But here with this fancy while loop that is not possible. There is no box in the box in the box happening like with recursion.</p>
  
  <p>I don't really want to have to add properties (or instance variables) to the TreeNode object as this should be re-usable in a generic way for any kind of object graph.</p>
  
  <p>Does anyone have an idea how to do this? Must I introduce another array to keep track of visited nodes?</p>