viernes, 18 de junio de 2010

General Tree - postorder

General Tree Node

public class Node
{
   char element;
   Node firstChild;
   Node nextSibling;

   Node(){}
   Node(char element)
   {
      this.element = element;
   }
}


Postorder visits the root last.

For general tree: do a postorder traversal each of the subtrees of the root one-by-one in the order given; and then visit the root.



public void postorder(Node node)
{
   Node child;
   if(node != null)
   {
      child = node.firstChild;
      if(child != null)
         postorder(child);
      System.out.print(node.element +", ");
      postorder(node.nextSibling);
   }
}

Test:

public static void main(String args[])
{

   GTree T2 = new GTree ('A');
   T2.root.firstChild = new Node('B');
   T2.root.firstChild.nextSibling = new Node('C');
   T2.root.firstChild.nextSibling.nextSibling = new Node('D');
   T2.root.firstChild.firstChild = new Node('E');
   T2.root.firstChild.firstChild.nextSibling = new Node('F');
   T2.root.firstChild.nextSibling.firstChild = new Node('G');

   System.out.println("\n postorder: visit others, then print root");
   T2.postorder(T2.root);
}

No hay comentarios:

Publicar un comentario