Пример #1
0
 /**
  * Traverses a tree breadth-first, printing each node as it is visited.
  * Uses a queue to keep track of the nodes to be visited.
  *
  * @param object ITree $tree The tree to traverse.
  */
 public static function breadthFirstTraversal(ITree $tree)
 {
     $queue = new QueueAsLinkedList();
     if (!$tree->isEmpty()) {
         $queue->enqueue($tree);
     }
     while (!$queue->isEmpty()) {
         $t = $queue->dequeue();
         printf("%s\n", str($t->getKey()));
         for ($i = 0; $i < $t->getDegree(); ++$i) {
             $subTree = $t->getSubtree($i);
             if (!$subTree->isEmpty()) {
                 $queue->enqueue($subTree);
             }
         }
     }
 }
Пример #2
0
 /**
  * Tree test program.
  *
  * param tree The tree to test.
  */
 public static function test(ITree $tree)
 {
     printf("AbstractTree test program.\n");
     printf("Breadth-First traversal\n");
     $tree->breadthFirstTraversal(new PrintingVisitor(STDOUT));
     printf("Preorder traversal\n");
     $tree->depthFirstTraversal(new PreOrder(new PrintingVisitor(STDOUT)));
     printf("Inorder traversal\n");
     $tree->depthFirstTraversal(new InOrder(new PrintingVisitor(STDOUT)));
     printf("Postorder traversal\n");
     $tree->depthFirstTraversal(new PostOrder(new PrintingVisitor(STDOUT)));
     printf("Using foreach\n");
     foreach ($tree as $obj) {
         printf("%s\n", str($obj));
     }
     printf("Using reduce\n");
     $tree->reduce(create_function('$sum,$obj', 'printf("%s\\n", str($obj));'), '');
     printf("Using accept\n");
     $tree->accept(new ReducingVisitor(create_function('$sum,$obj', 'printf("%s\\n", str($obj));'), ''));
 }