PHP递归方法实现前序、中序、后序遍历二叉树

二叉树是每个节点最多有两个子树的树结构。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。

<?php

namespace app\data_structure\tree;

/**
 * php递归方法方法实现前序、中序、后序遍历二叉树
 * 二叉树是每个节点最多有两个子树的树结构。通常子树被称作"左子树"(left subtree)和"右子树"(right subtree)
 * https://www.cnblogs.com/rxbook/p/10441931.html
 */
class BinaryTree1
{
    public $value;
    public $left;
    public $right;
}

/**
 * 前序遍历
 * 根节点 ---> 左子树 ---> 右子树
 */
function preorder($root)
{
    if (empty($root)) {
        return;
    }

    echo $root->value . ' ';//输出根节点
    preOrder($root->left);
    preOrder($root->right);
}

/**
 * 中序遍历
 * 左子树---> 根节点 ---> 右子树
 */
function inorder($root)
{
    if (empty($root)) {
        return;
    }

    inorder($root->left);
    echo $root->value . ' ';//输出根节点
    inorder($root->right);
}

/**
 * 后序遍历
 * 左子树 ---> 右子树 ---> 根节点
 */
function tailorder($root)
{
    if (empty($root)) {
        return;
    }

    tailorder($root->left);
    tailorder($root->right);
    echo $root->value . ' ';//输出根节点
}

//测试
$a = new BinaryTree1();
$b = new BinaryTree1();
$c = new BinaryTree1();
$d = new BinaryTree1();
$e = new BinaryTree1();
$f = new BinaryTree1();

$a->value = 'A';
$b->value = 'B';
$c->value = 'C';
$d->value = 'D';
$e->value = 'E';
$f->value = 'F';

$a->left = $b;
$a->right = $c;
$b->left = $d;
$c->left = $e;
$c->right = $f;

echo "php递归方法实现前序、中序、后序遍历二叉树: \n";
echo "前序遍历:";
preorder($a); //A B D C E F
echo "\n";

echo "中序遍历:";
inorder($a);//D B A E C F
echo "\n";

echo "后序遍历:";
tailorder($a);//D B E F C A
echo "\n";

结果:

 

posted @ 2019-02-27 10:25  码农骆驼  阅读(1018)  评论(0编辑  收藏  举报