PHP implementation of two fork tree depth and breadth first traversal algorithm steps

Source: Internet
Author: User
Tags autoload spl
This time to bring you PHP implementation of two fork tree depth and breadth first traversal algorithm steps, PHP implementation of the two-tree depth and breadth of priority traversal of the considerations are what, the following is the actual case, take a look.

Objective:

Depth-First traversal : Drill down to every possible branch path to no further depth, and each node can be accessed only once. It is particularly important to note that the depth-first traversal of a binary tree is special and can be subdivided into first-order traversal, middle-sequence traversal, and post-order traversal. Specify the following:

Pre-sequence traversal: The right subtree, left dial hand tree, root node
Middle Sequence traversal: the right subtree, the root node, left dial hand tree
Post-post traversal: root node, right subtree, left dial hand tree

breadth-First traversal : Also called the hierarchical traversal, from the top down to each layer in turn, in each layer, from left to right (can also from right to left) access to the node, access to the next layer on the end, until no nodes can be accessed.

For example, for this tree:

Depth-First traversal:

Pre-sequence Traversal: 10 8 7 9 12 11 13
Middle Sequence Traversal: 7 8 9 10 11 12 13
Post-Post traversal: 7 9 8 11 13 12 10

Breadth-First traversal:

Hierarchical traversal: 10 8 12 7 9 11 13

The general practice of non-recursion for the depth-first traversal of binary trees is to use the stack, which is the common practice of the non-recursion of breadth-first traversal is to adopt the queue.

Depth-First traversal:

1. Pre-sequence traversal:

/*** Pre-order Traversal (recursive method) */private function Pre_order1 ($root) {if (!is_null ($root)) {//Use the constant function here to get the current function name, the advantage is that if you modify the function name      , the implementation of the inside does not need to modify $function = function; Echo $root->key.      " ";      $this-$function ($root->left);    $this-$function ($root->right); }}/*** Pre-order traversal (non-recursive method) * because you have to back up after traversing the root node, you must save it. Taking into account the characteristics of LIFO, the use of stack storage.    */private function Pre_order2 ($root) {//$stack = new Splstack ();    $stack->push ($root);    while (! $stack->isempty ()) {//$node = $stack->pop (); echo $node->key. '    ';    if (!is_null ($node->right)) {//$stack->push ($node->right);    }//if (!is_null ($node->left)) {//$stack->push ($node->left);    }//} if (Is_null ($root)) {return;    } $stack = new Splstack ();    $node = $root;        while (!is_null ($node) | |-$stack->isempty ()) {while (!is_null ($node)) {//should be stored in the stack as long as the node is not empty, regardless of its left and right nodes $stack->push($node); Echo $node->key.        ' ';      $node = $node->left;      } $node = $stack->pop ();    $node = $node->right;    }}//Pre-sequence traversal public function preorder () {//The tree attribute in the object holds a reference//$this->pre_order1 ($this->tree->root) $this->pre_order2 ($this->tree->root);}

Description: 1, I have all the traversal methods encapsulated in a class traverse inside. 2, Pre_order2 method, in the process of using the stack, I use the PHP standard library SPL provided by the Splstack, if you are accustomed to using arrays, you can use array_push() and array_pop() simulation implementation.

2, the middle sequence traversal:

/*** (recursive method) */private function Mid_order1 ($root) {    if (!is_null ($root)) {      $function = function;      $this-$function ($root->left);      Echo $root->key. " ";      $this-$function ($root->right);}    /*** in-sequence traversal (non-recursive method) * because you have to back up after traversing the root node, you must save it. Taking into account the characteristics of LIFO, the use of stack storage. */private function Mid_order2 ($root) {    if (Is_null ($root)) {      return;    }    $stack = new Splstack ();    $node = $root;    while (!is_null ($node) | |, $stack->isempty ()) {      while (!is_null ($node)) {        $stack->push ($node);        $node = $node->left;      }      $node = $stack->pop ();      Echo $node->key. ' ';      $node = $node->right;    }} Middle order traverse Public Function Midorder () {    //    $this->mid_order1 ($this->tree->root);    $this->mid_order2 ($this->tree->root);}

3. Post-sequential traversal:

/*** Post-procedure traversal (recursive method) */private function Post_order1 ($root) {if (!is_null ($root)) {$function = function;      $this-$function ($root->left);      $this-$function ($root->right); Echo $root->key.    " "; }}/*** Post-order traversal (non-recursive method) * because you have to back up after traversing the root node, you must save it. Taking into account the characteristics of LIFO, the use of stack storage.      * Since it is difficult to jump to the right child node after accessing the left Dial hand node, here is an identity lastvisited to identify the last visited node */private function Post_order2 ($root) {if (Is_null ($root)) {    Return    } $node = $root;    $stack = new Splstack ();    Save the last accessed node reference $lastVisited = NULL;    $stack->push ($node); while (! $stack->isempty ()) {$node = $stack->top ();//Gets the top element of the stack but does not eject if ($node->left = = NULL && $node- >right = = NULL) | | ($node->right = = NULL && $lastVisited = = $node->left) | | ($lastVisited = = $node->right)) {echo $node->key. '        ';        $lastVisited = $node;      $stack->pop ();        }else{if ($node->right) {$stack->push ($node->right);  } if ($node->left) {        $stack->push ($node->left);    }}}}//post-traverse public function Postorder () {//$this->post_order1 ($this->tree->root); $this->post_order2 ($this->tree->root);}

Breadth-First traversal:

1. Hierarchy Traversal:

/*** Hierarchy Traversal (recursive method) * Due to layer by layer traversal, so the number of layers of the pass tree */private function Level_order1 ($root, $level) {if ($root = = NULL | | $level < 1) {    Return } if ($level = = 1) {echo $root->key. '      ';    Return    } if (!is_null ($root->left)) {$this->level_order1 ($root->left, $level-1);    } if (!is_null ($root->right)) {$this->level_order1 ($root->right, $level-1); }}/*** hierarchy Traversal (non-recursive method) * Each layer of output elements from left to right needs to be stored with first-in, out-of-the-way features, so use queue storage.    */private function Level_order2 ($root) {if (Is_null ($root)) {return;    } $node = $root;      Using the queue implementation//$queue = Array ();//Array_push ($queue, $node);////while (!is_null ($node = Array_shift ($queue))) {// echo $node->key. ' ';//if (!is_null ($node->left)) {//Array_push ($queue, $node->left);//}//if (!is_null ($node    right) {//Array_push ($queue, $node->right);//}//} $queue = new Splqueue ();    $queue->enqueue ($node); while (! $queue->isempty ()) {$node = $queueDequeue (); echo $node->key. '      ';      if (!is_null ($node->left)) {$queue->enqueue ($node->left);      } if (!is_null ($node->right)) {$queue->enqueue ($node->right); The}}//hierarchy traverses public function Levelorder () {//$level = $this->getdepth ($this->tree->root);//for ($i = 1; $i & Lt;= $level, $i + +) {//$this->level_order1 ($this->tree->root, $i);/} $this->level_order2 ($this Tree->root);}    Gets the number of layers of the tree private Function getdepth ($root) {if (Is_null ($root)) {return 0;    } $left = Getdepth ($root-left);    $right = getdepth ($root, right);    $depth = ($left > $right? $left: $right) + 1; return $depth;}

Description: In the Level_order2 method, during the use of the queue, I used the splqueue provided by the PHP standard library SPL, which can be used and emulated if you are accustomed to using arrays array_push() array_shift() .

Use:

Now let's take a look at the client code:

Class client{public  static function Main ()  {    try {      //implement file's auto-load      function autoload ($class)      {        include Strtolower ($class). '. php ';      }      Spl_autoload_register (' AutoLoad ');      $arr = Array (ten, 8, 7, 9, one, all);      $tree = new Bst ()//      $tree = new AVL ();//      $tree = new RBT ()      ; $tree->init ($arr);      $traverse = new Traverse ($tree);      $traverse->preorder ();//      $traverse->midorder ();//      $traverse->postorder ();//      $traverse- >levelorder ();    } catch (Exception $e) {      echo $e->getmessage ();}}  } Client::main ();

Add:

1. Three classes used in the client Bst, AVL, Rbt you can refer to the previous article: "PHP implementation of drawing binary tree graphics display function in detail"

2. Why do I recommend that you use the and as provided in the SPL standard library splstack splqueue ? This is what I saw in an article: although we can use traditional variable types to describe data structures, such as using arrays to describe stacks (Strack)-and then use the corresponding way pop and push ( array_pop() , array_push() ), but you have to be careful at all times, Because, after all, they are not specifically designed to describe data structures – a single misoperation can destroy the stack. The Splstack object of SPL describes the data strictly in the form of stacks and provides corresponding methods. At the same time, such code should also be able to understand it in the Operation Stack rather than an array, so that your partner can better understand the corresponding code, and it is faster. Original address: PHP SPL, missing gems

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

PHP Simple Selection Sort case detailed

PHP Implementation Huffman encoding/decoding steps

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.