<?php
class TreeNode
{
public $val = null;
public $left = null;
public $right = null;
function __construct($value)
{
$this->val = $value;
}
}
class BinaryTree
{
private $arr, $len;
public function createTree($arr)
{
$this->arr = (array)$arr;
$this->len = count($this->arr);
$root = new TreeNode($this->arr[0]); //数组第一个为根结点
$root->left = $this->generate(1); //根据数组下标进行构建二叉树
$root->right = $this->generate(2);
return $root; //返回根结点
}
/**
* 构建二叉树递归函数
*/
private function generate($index)
{
if ($this->arr[$index] == '#') { //为#则构建节点后直接返回
$node = new TreeNode(null);
return $node;
}
$node = new TreeNode($this->arr[$index]); //有值则按照具体值构建子节点
$key = $index * 2 + 1; //二叉树在数组上的显示是2倍跳着的
if ($key < $this->len) { //防止数组越界
$node->left = $this->generate($key++);
}
if ($key < $this->len) {
$node->right = $this->generate($key);
}
return $node;
}
/**
* 前序遍历
*/
public function getTree($root)
{
if ($root) {
echo $root->val;
$this->getTree($root->left);
$this->getTree($root->right);
}
}
}
$tree = new BinaryTree();
$arr = [1, 2, 3, 4, '#', 5, '#', 6, 7, '#', '#', 8, 9];
$root = $tree->createTree($arr);
function preOrder($root){
$stack = array();
array_push($stack, $root);
while (!empty($stack)) {
$centerNode = array_pop($stack);
echo $centerNode->val;
if (!is_null($centerNode->right)) {
array_push($stack, $centerNode->right);
}
if (!is_null($centerNode->left)) {
array_push($stack, $centerNode->left);
}
}
}
function inOrder($root) {
$stack = array();
$centerNode = $root;
while (!empty($stack) || !is_null($centerNode)) {
while (!is_null($centerNode)) {
array_push($stack, $centerNode);
$centerNode = $centerNode->left;
}
$centerNode = array_pop($stack);
echo $centerNode->val;
$centerNode = $centerNode->right;
}
}
function tailOrder($root){
$stack = $outstack = array();
array_push($stack, $root);
while (!empty($stack) || !is_null($centerNode)) {
$centerNode = array_pop($stack);
array_push($outstack, $centerNode);
if (!is_null($centerNode->left)) {
array_push($stack, $centerNode->left);
}
if (!is_null($centerNode->right)) {
array_push($stack, $centerNode->right);
}
}
while (!empty($outstack)) {
$centerNode = array_pop($outstack);
echo $centerNode->val;
}
}
// tailOrder($root);