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