PHP实现二叉树深度优先遍历(前序、中序、后序)和广度优先遍历(层次)实例详解


Posted in PHP onApril 20, 2018

本文实例讲述了PHP实现二叉树深度优先遍历(前序、中序、后序)和广度优先遍历(层次)。分享给大家供大家参考,具体如下:

前言:

深度优先遍历:对每一个可能的分支路径深入到不能再深入为止,而且每个结点只能访问一次。要特别注意的是,二叉树的深度优先遍历比较特殊,可以细分为先序遍历、中序遍历、后序遍历。具体说明如下:

前序遍历:根节点->左子树->右子树
中序遍历:左子树->根节点->右子树
后序遍历:左子树->右子树->根节点

广度优先遍历:又叫层次遍历,从上往下对每一层依次访问,在每一层中,从左往右(也可以从右往左)访问结点,访问完一层就进入下一层,直到没有结点可以访问为止。

例如对于一下这棵树:

PHP实现二叉树深度优先遍历(前序、中序、后序)和广度优先遍历(层次)实例详解

深度优先遍历:

前序遍历:10 8 7 9 12 11 13
中序遍历:7 8 9 10 11 12 13
后序遍历:7 9 8 11 13 12 10

广度优先遍历:

层次遍历:10 8 12 7 9 11 13

二叉树的深度优先遍历的非递归的通用做法是采用栈,广度优先遍历的非递归的通用做法是采用队列。

深度优先遍历:

1、前序遍历:

/**
* 前序遍历(递归方法)
*/
private function pre_order1($root)
{
    if (!is_null($root)) {
      //这里用到常量__FUNCTION__,获取当前函数名,好处是假如修改函数名的时候,里面的实现不用修改
      $function = __FUNCTION__;
      echo $root->key . " ";
      $this->$function($root->left);
      $this->$function($root->right);
    }
}
/**
* 前序遍历(非递归方法)
* 因为当遍历过根节点之后还要回来,所以必须将其存起来。考虑到后进先出的特点,选用栈存储。
*/
private function pre_order2($root)
{
    //    $stack = new splstack();
    //    $stack->push($root);
    //    while(!$stack->isEmpty()){
    //      $node = $stack->pop();
    //      echo $node->key.' ';
    //      if(!is_null($node->right)){
    //        $stack->push($node->right);
    //      }
    //      if(!is_null($node->left)){
    //        $stack->push($node->left);
    //      }
    //    }
    if (is_null($root)) {
      return;
    }
    $stack = new splstack();
    $node = $root;
    while (!is_null($node) || !$stack->isEmpty()) {
      while (!is_null($node)) {
        //只要结点不为空就应该入栈保存,与其左右结点无关
        $stack->push($node);
        echo $node->key . ' ';
        $node = $node->left;
      }
      $node = $stack->pop();
      $node = $node->right;
    }
}
//前序遍历
public function PreOrder()
{
    // 所在对象中的tree属性保存了一个树的引用
    //   $this->pre_order1($this->tree->root);
    $this->pre_order2($this->tree->root);
}

说明:1、我将所有的遍历方法都封装在一个类 traverse 里面了。2、pre_order2方法中,在使用栈的过程中,我使用的是PHP标准库SPL提供的splstack,如果你们习惯使用数组的话,可以使用 array_push() array_pop() 模拟实现。

2、中序遍历:

/**
* 中序遍历(递归方法)
*/
private function mid_order1($root)
{
    if (!is_null($root)) {
      $function = __FUNCTION__;
      $this->$function($root->left);
      echo $root->key . " ";
      $this->$function($root->right);
    }
}
/**
* 中序遍历(非递归方法)
* 因为当遍历过根节点之后还要回来,所以必须将其存起来。考虑到后进先出的特点,选用栈存储。
*/
private function mid_order2($root)
{
    if (is_null($root)) {
      return;
    }
    $stack = new splstack();
    $node = $root;
    while (!is_null($node) || !$stack->isEmpty()) {
      while (!is_null($node)) {
        $stack->push($node);
        $node = $node->left;
      }
      $node = $stack->pop();
      echo $node->key . ' ';
      $node = $node->right;
    }
}
//中序遍历
public function MidOrder()
{
    //    $this->mid_order1($this->tree->root);
    $this->mid_order2($this->tree->root);
}

3、后序遍历:

/**
* 后序遍历(递归方法)
*/
private function post_order1($root)
{
    if (!is_null($root)) {
      $function = __FUNCTION__;
      $this->$function($root->left);
      $this->$function($root->right);
      echo $root->key . " ";
    }
}
/**
* 后序遍历(非递归方法)
* 因为当遍历过根节点之后还要回来,所以必须将其存起来。考虑到后进先出的特点,选用栈存储。
* 由于在访问了左子节点后怎么跳到右子节点是难点,这里使用一个标识lastVisited来标识上一次访问的结点
*/
private function post_order2($root)
{
    if (is_null($root)) {
      return;
    }
    $node = $root;
    $stack = new splstack();
    //保存上一次访问的结点引用
    $lastVisited = NULL;
    $stack->push($node);
    while(!$stack->isEmpty()){
      $node = $stack->top();//获取栈顶元素但不弹出
      if(($node->left == NULL && $node->right == NULL) || ($node->right == NULL && $lastVisited == $node->left) || ($lastVisited == $node->right)){
        echo $node->key.' ';
        $lastVisited = $node;
        $stack->pop();
      }else{
        if($node->right){
          $stack->push($node->right);
        }
        if($node->left){
          $stack->push($node->left);
        }
      }
    }
}
//后序遍历
public function PostOrder()
{
    //    $this->post_order1($this->tree->root);
    $this->post_order2($this->tree->root);
}

广度优先遍历:

1、层次遍历:

/**
* 层次遍历(递归方法)
* 由于是按层逐层遍历,因此传递树的层数
*/
private function level_order1($root,$level){
    if($root == NULL || $level < 1){
      return;
    }
    if($level == 1){
      echo $root->key.' ';
      return;
    }
    if(!is_null($root->left)){
      $this->level_order1($root->left,$level - 1);
    }
    if(!is_null($root->right)){
      $this->level_order1($root->right,$level - 1);
    }
}
/**
* 层次遍历(非递归方法)
* 每一层从左向右输出
元素需要储存有先进先出的特性,所以选用队列存储。
*/
private function level_order2($root){
    if(is_null($root)){
      return;
    }
    $node = $root;
    //利用队列实现
//    $queue = array();
//    array_push($queue,$node);
//
//    while(!is_null($node = array_shift($queue))){
//      echo $node->key.' ';
//      if(!is_null($node->left)){
//        array_push($queue,$node->left);
//      }
//      if(!is_null($node->right)){
//        array_push($queue,$node->right);
//      }
//    }
    $queue = new splqueue();
    $queue->enqueue($node);
    while(!$queue->isEmpty()){
      $node = $queue->dequeue();
      echo $node->key.' ';
      if (!is_null($node->left)) {
        $queue->enqueue($node->left);
      }
      if (!is_null($node->right)) {
        $queue->enqueue($node->right);
      }
    }
}
//层次遍历
public function LevelOrder(){
//    $level = $this->getdepth($this->tree->root);
//    for($i = 1;$i <= $level;$i ++){
//      $this->level_order1($this->tree->root,$i);
//    }
    $this->level_order2($this->tree->root);
}
//获取树的层数
private function getdepth($root){
    if(is_null($root)){
      return 0;
    }
    $left = getdepth($root -> left);
    $right = getdepth($root -> right);
    $depth = ($left > $right ? $left : $right) + 1;
    return $depth;
}

说明:level_order2方法中,在使用队列的过程中,我使用的是PHP标准库SPL提供的splqueue,如果你们习惯使用数组的话,可以使用 array_push() array_shift() 模拟实现。

使用:

现在我们来看看客户端代码:

class Client
{
  public static function Main()
  {
    try {
      //实现文件的自动加载
      function autoload($class)
      {
        include strtolower($class) . '.php';
      }
      spl_autoload_register('autoload');
      $arr = array(10, 8, 12, 7, 9, 11, 13);
      $tree = new Bst();
//      $tree = new Avl();
//      $tree = new Rbt();
      $tree->init($arr);
      $traverse = new traverse($tree);
      $traverse->PreOrder();
//      $traverse->MidOrder();
//      $traverse->PostOrder();
//      $traverse->LevelOrder();
    } catch (Exception $e) {
      echo $e->getMessage();
    }
  }
}
CLient::Main();

补充:

1. 在客户端中所使用的三个类 Bst、Avl、Rbt 大家可以参考前面一篇:《PHP实现绘制二叉树图形显示功能详解》

2. 为什么我推荐大家使用SPL标准库中提供的splstacksplqueue呢?这是我在某一篇文章中看到的:虽然我们可以使用传统的变量类型来描述数据结构,例如用数组来描述堆栈(Strack)? 然后使用对应的方式 pop 和 push(array_pop()array_push()),但你得时刻小心,因为毕竟它们不是专门用于描述数据结构的 ? 一次误操作就有可能破坏该堆栈。而 SPL 的 SplStack 对象则严格以堆栈的形式描述数据,并提供对应的方法。同时,这样的代码应该也能理解它在操作堆栈而非某个数组,从而能让你的同伴更好的理解相应的代码,并且它更快。原文地址:PHP SPL,遗落的宝石

3. 本文相关参考文章: 《C语言二叉树常见操作详解【前序,中序,后序,层次遍历及非递归查找,统计个数,比较,求深度】》、《Java实现二叉树的深度优先遍历和广度优先遍历算法示例》

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
php面向对象全攻略 (二) 实例化对象 使用对象成员
Sep 30 PHP
php下将XML转换为数组
Jan 01 PHP
php array_pop()数组函数将数组最后一个单元弹出(出栈)
Jul 12 PHP
PHP写的求多项式导数的函数代码
Jul 04 PHP
用C/C++扩展你的PHP 为你的php增加功能
Sep 06 PHP
php异常处理使用示例
Feb 25 PHP
PHP过滤黑名单关键字的方法
Dec 01 PHP
求帮忙修改个php curl模拟post请求内容后并下载文件的解决思路
Sep 20 PHP
利用Fix Rss Feeds插件修复WordPress的Feed显示错误
Dec 19 PHP
PHP基于Redis消息队列实现发布微博的方法
May 03 PHP
php-fpm服务启动脚本的方法
Apr 27 PHP
用php定义一个数组最简单的方法
Oct 04 PHP
PHP SPL 被遗落的宝石【SPL应用浅析】
Apr 20 #PHP
Laravel 加载第三方类库的方法
Apr 20 #PHP
PHP迭代器和迭代的实现与使用方法分析
Apr 19 #PHP
详解php curl带有csrf-token验证模拟提交方法
Apr 18 #PHP
php-app开发接口加密详解
Apr 18 #PHP
PHPMAILER实现PHP发邮件功能
Apr 18 #PHP
PHP实现数据库的增删查改功能及完整代码
Apr 18 #PHP
You might like
基于Zend的Config机制的应用分析
2013/05/02 PHP
Laravel获取当前请求的控制器和方法以及中间件的例子
2019/10/11 PHP
php 多个变量指向同一个引用($b = &amp;$a)用法分析
2019/11/13 PHP
prototype.js的Ajax对象
2006/09/23 Javascript
Jquery跨域获得Json时invalid label错误的解决办法
2011/01/11 Javascript
jQuery 开发者应该注意的9个错误
2012/05/03 Javascript
jquery slibings选取同级其他元素的实现代码
2013/11/15 Javascript
实现音乐播放器的代码(html5+css3+jquery)
2015/08/04 Javascript
谈谈JSON对象和字符串之间的相互转换JSON.stringify(obj)和JSON.parse(string)
2015/10/01 Javascript
JS基于VML技术实现的五角星礼花效果代码
2015/10/26 Javascript
javascript+html5+css3自定义弹出窗口效果
2017/10/26 Javascript
vue项目关闭eslint校验
2018/03/21 Javascript
解决vue项目打包后提示图片文件路径错误的问题
2018/07/04 Javascript
js判断浏览器的环境(pc端,移动端,还是微信浏览器)
2020/12/24 Javascript
[03:46]DAC趣味视频-中文考试.mp4
2017/04/02 DOTA
python中bisect模块用法实例
2014/09/25 Python
在Python的Django框架中加载模版的方法
2015/07/16 Python
MySQL适配器PyMySQL详解
2017/09/20 Python
python用户管理系统的实例讲解
2017/12/23 Python
Python + selenium自动化环境搭建的完整步骤
2018/05/19 Python
Django保护敏感信息的方法示例
2019/05/09 Python
django 捕获异常和日志系统过程详解
2019/07/18 Python
python opencv 实现对图像边缘扩充
2020/01/19 Python
Python读取yaml文件的详细教程
2020/07/21 Python
HTML5自定义视频播放器源码
2020/01/06 HTML / CSS
俄罗斯三星品牌商店:Samsungstore
2020/04/05 全球购物
写给妈妈的道歉信
2014/01/11 职场文书
《争吵》教学反思
2014/02/15 职场文书
学校领导班子群众路线整改措施
2014/09/16 职场文书
县政府班子个人对照检查材料
2014/10/05 职场文书
判缓刑人员个人思想汇报
2014/10/10 职场文书
2015年销售内勤工作总结
2015/04/27 职场文书
2015年体检中心工作总结
2015/05/27 职场文书
2016幼儿园毕业感言
2015/12/08 职场文书
大学生创业计划书常用模板
2019/08/07 职场文书
学会Python数据可视化必须尝试这7个库
2021/06/16 Python