<?php
/*
* 完成二叉树的深度优先遍历
* 就是二叉树从根节点到叶子节点,是二叉树的先跟(先序)遍历
* 递归与非递归解法
* */
//二叉树的结构
class TreeNode{
var $val;
var $left = NULL;
var $right = NULL;
function __construct($val){
$this->val = $val;
}
}
//递归解法
function FindPath1($root)
{
if(!empty($root)){
echo $root->val;
FindPath($root->left);
FindPath($root->right);
}else{
return;
}
}
//非递归解法
//使用栈来完成,先压右子树,再压左子树
function FindPath2($root)
{
$arr = [];
while(!empty($root)){
echo $root->val;
if(!empty($root->right)){
array_push($arr,$root->right);
}if(!empty($root->left)){
array_push($arr,$root->left);
}
$root = array_pop($arr);
}
}
//测试
$a = new TreeNode(1);
$b = new TreeNode(2);
$c = new TreeNode(3);
$d = new TreeNode(4);
$e = new TreeNode(5);
$f = new TreeNode(6);
$g = new TreeNode(7);
$h = new TreeNode(8);
$i = new TreeNode(9);
$j = new TreeNode(10);
$a->left = $b;
$a->right = $c;
$b->left = $d;
$b->right = $e;
$c->left = $f;
$c->right = $g;
$d->left = $h;
$d->right = $i;
$f->left = $j;
FindPath2($a);
PHP 实现二叉树的深度优先遍历
最新推荐文章于 2021-08-07 19:45:19 发布