广度有优先可以实现二叉树的层级遍历
  • 优先将 根节点 加入队列
  • 取出来一个节点进行处理
  • 依次词节点的 子节点入队 没有就不放入
  • 队列非空则 继续 重复取出一个节点加入子节点 知道结束
点击查看代码
class Node
{
    public $value;
    public $child_left;
    public $child_right;
}

$a = new Node();
$b = new Node();
$c = new Node();
$d = new Node();
$e = new Node();
$f = new Node();
$g = new Node();
$h = new Node();
$i = new Node();

$a->value = '1';

$b->value = '2';
$c->value = '3';

$d->value = '4';
$e->value = '5';

$f->value = '6';
$g->value = '7';


$a->child_left = $b;
$a->child_right = $c;

//   2
// 4  5

$b->child_left = $d;
$b->child_right = $e;


//   3
//  6   7

$c->child_left = $f;
$c->child_right = $g;

function bfs($root)
{
    $queue = [ $root];
    while (count($queue)) {

        for ($i = 0; $i < count($queue); $i++) {

            $top = array_shift($queue);
            echo $top->value, PHP_EOL;

            if ($top->child_left) {
                array_push($queue, $top->child_left);
            }

            if ($top->child_right) {
                array_push($queue, $top->child_right);
            }
        }
    }
}

深度优先使用栈 和广度优先一样

  • 放入跟节点
  • 拿出节点
  • 放入子节点
  • 栈非空 弹出节点 加入子节点
点击查看代码
function dfs($root)
{
    $queue = [$root];
    while (count($queue)) {
        for ($i = 0; $i < count($queue); $i++) {

            $top = array_pop($queue);
            echo $top->value, PHP_EOL;

            if ($top->child_left) {
                array_push($queue, $top->child_left);
            }

            if ($top->child_right) {
                array_push($queue, $top->child_right);
            }
        }
    }
}

原文地址:http://www.cnblogs.com/guanchaoguo/p/16845135.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性