二叉树遍历,前序、中序、后序

<?php

class BinaryTree
{

    public $data;
    public $left = null;
    public $right = null;

    public function __construct($element)
    {
        if (!empty($element)) {
            $this->data = $element;
        }
    }

    //先序遍历
    public function pre($root)
    {
        if (null !== $root->data) {
            var_dump($root->data);
            if (null !== $root->left) {
                $this->pre($root->left);
            }
            if (null !== $root->right) {
                $this->pre($root->right);
            }
        }
    }

    //中序遍历
    public function mid($root)
    {
        if (null !== $root->data) {
            if (null !== $root->left) {
                $this->mid($root->left);
            }
            var_dump($root->data);
            if (null !== $root->right) {
                $this->mid($root->right);
            }
        }
    }


    //后序遍历
    public function postorder($root)
    {
        if (null !== $root->data) {
            if (null !== $root->left) {
                $this->postorder($root->left);
            }
            if (null !== $root->right) {
                $this->postorder($root->right);
            }
            var_dump($root->data);
        }
    }
}

//每个节点实例化对象,使其实例化的每个对象包含根节点,左节点,右节点属性
$a = new BinaryTree('A');
$b = new BinaryTree('B');
$c = new BinaryTree('C');
$d = new BinaryTree('D');
$e = new BinaryTree('E');
//构造二叉树
$a->left = $b;
$a->right = $c;
$c->left = $d;
$d->right = $e;


$a->pre($a);//前序遍历
echo "<br/>"; 
$a->mid($a);//中序遍历
echo "<br/>";
$a->postorder($a);//后序遍历


?>

树:
      A                    
      * *                   
     *   *                  
    B     C                
         *                   
        *                    
       D                    
        *                    
          *E     

结果:

//先序遍历的结果
string(1) "A" string(1) "B" string(1) "C" string(1) "D" string(1) "E" 
//中序遍历的结果
string(1) "B" string(1) "A" string(1) "D" string(1) "E" string(1) "C" 
//后序列遍历的结果
string(1) "B" string(1) "E" string(1) "D" string(1) "C" string(1) "A"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值