Java: recorrer una estructura de árbol usando Stacks sin llamadas recursivas

Consideramos una estructura de árbol, formada por objetos que heredan de Node. Cada objeto, subclase de Node, puede tener hijos que a su vez son subclases de Node.

Podemos recorrer el árbol de objetos, sin utilizar llamadas recursivas, utilizando el código que se muestra a continuación:

/**
* Returns a {@link Stack} having a Tree ordered in Depth First whose root is passed as the Parameter
*
* @param The implementation of {@link Node}
* @param treeRoot The root of the tree
* @return The {@link Stack} of T
*/
public static Stack depthFirstOrder(final T treeRoot)
{
   // Main stack, where the important stuff go
   Stack mainStack = new Stack();

   // Temp child stack, where we store children of before it gets put to the mainStack
   Stack tempChildStack = new Stack();

   mainStack.push(treeRoot);   // Put the tree root
   tempChildStack.addAll(treeRoot.getChildren()); // Put the children to the temp

   // Loop until no more children in the temp stack
   while (!tempChildStack.isEmpty())
   {
      T node = (T) tempChildStack.pop();   // Keep popping from the temp stack..
      mainStack.push(node);   // .. and Push to the main stack..
      tempChildStack.addAll(node.getChildren()); // .. while adding children to temp
   }

   // Now temp stack is empty and mainStack has things in DFS order!
   return mainStack;
}

Vía | gunith

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>