?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相关内容感兴趣的读者可查看本站专题:《PHP数据结构与算法教程》、《php程序设计算法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP常用遍历算法与技巧总结》及《PHP数学运算技巧总结》