本文實(shí)例講述了PHP實(shí)現(xiàn)按之字形順序打印二叉樹的方法。分享給大家供大家參考,具體如下:
問題
請實(shí)現(xiàn)一個函數(shù)按照之字形打印二叉樹,即第一行按照從左到右的順序打印,第二層按照從右至左的順序打印,第三行按照從左到右的順序打印,其他行以此類推。
解決思路
使用兩個棧
實(shí)現(xiàn)代碼
- <?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程序設(shè)計有所幫助。