PHP using the z-glyph sequence to print the binary tree steps

Source: Internet
Author: User
Tags php class
This time for everyone to bring PHP using the Z-shape sequence to print the binary tree step by bit, PHP using the Z-shape sequence to print the binary tree note what, the following is the actual case, take a look.

Problem

Implement a function to print a binary tree by its glyph, that is, the first line is printed from left to right, the second layer is printed from right to left, the third line is printed from left to right, and so on in the other rows.

Solution Ideas

Use of two stacks

Implementation code

<?php/*class treenode{var $val;  var $left = NULL;  var $right = NULL;  function construct ($val) {$this->val = $val;  }}*/function Myprint ($pRoot) {if ($pRoot = = NULL) return [];  $current = 0;  $next = 1;  $stack [0] = array ();  $stack [1] = array ();  $resultQueue = Array ();  Array_push ($stack [0], $pRoot);  $i = 0;  $result = Array ();  $result [0]= Array ();    while (!empty ($stack [0]) | |!empty ($stack [1])) {$node = Array_pop ($stack [$current]);    Array_push ($result [$i], $node->val);    Var_dump ($resultQueue); echo "</br>";      if ($current = = 0) {if ($node->left! = NULL) Array_push ($stack [$next], $node->left);    if ($node->right! = NULL) Array_push ($stack [$next], $node->right);      }else{if ($node->right! = NULL) Array_push ($stack [$next], $node->right);    if ($node->left! = NULL) Array_push ($stack [$next], $node->left);      } if (Empty ($stack [$current])) {$current = 1-$current; $next = 1-$next        if (!empty ($stack [0]) | |!empty ($stack [1])) {$i + +;      $result [$i] = array (); }}} return $result;}

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 Implementation MongoDB Singleton mode operation steps

Why is there a PHP Class soapclient not found problem and workaround

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.