您好,欢迎访问一九零五行业门户网

PHP使用Z字形顺序打印二叉树步骤详解

这次给大家带来php使用z字形顺序打印二叉树步骤详解,php使用z字形顺序打印二叉树的注意事项有哪些,下面就是实战案例,一起来看一下。
问题
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
解决思路
使用两个栈
实现代码
<?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; }
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
php实现mongodb单例模式操作类步骤详解
为什么有php class soapclient not found问题以及解决方法
以上就是php使用z字形顺序打印二叉树步骤详解的详细内容。
其它类似信息

推荐信息