php实现二叉树的创建以及前序/中序/后序遍历

<?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);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值