無論是身處學校還是步入社會,大家都嘗試過寫作吧,借助寫作也可以提高我們的語言組織能力。范文怎么寫才能發揮它最大的作用呢?下面是小編幫大家整理的優質范文,僅供參考,大家一起來看看吧。
php二叉樹遍歷代碼篇一
本文主要介紹了php實現的二叉樹遍歷算法,結合具體實例形式分析了php針對二叉樹的常用前序、中序及后序遍歷算法實現技巧,需要的朋友可以參考一下!想了解更多相關信息請持續關注我們應屆畢業生考試網!
<?php
class node {
public $value;
public $child_left;
public $child_right;
}
final class ergodic {
//前序遍歷:先訪問根節點,再遍歷左子樹,最后遍歷右子樹;并且在遍歷左右子樹時,仍需先遍歷根節點,然后訪問左子樹,最后遍歷右子樹
public static function preorder($root){
$stack = array();
array_push($stack, $root);
while(!empty($stack)){
$center_node = array_pop($stack);
echo $center_node->value . ' ';
//先把右子樹節點入棧,以確保左子樹節點先出棧
if($center_node->child_right != null) array_push($stack, $center_node->child_right);
if($center_node->child_left != null) array_push($stack, $center_node->child_left);
}
}
//中序遍歷:先遍歷左子樹、然后訪問根節點,最后遍歷右子樹;并且在遍歷左右子樹的時候。仍然是先遍歷左子樹,然后訪問根節點,最后遍歷右子樹
public static function midorder($root){
$stack = array();
$center_node = $root;
while (!empty($stack) || $center_node != null) {
while ($center_node != null) {
array_push($stack, $center_node);
$center_node = $center_node->child_left;
}
$center_node = array_pop($stack);
echo $center_node->value . ' ';
$center_node = $center_node->child_right;
}
}
//后序遍歷:先遍歷左子樹,然后遍歷右子樹,最后訪問根節點;同樣,在遍歷左右子樹的時候同樣要先遍歷左子樹,然后遍歷右子樹,最后訪問根節點
public static function endorder($root){
$push_stack = array();
$visit_stack = array();
array_push($push_stack, $root);
while (!empty($push_stack)) {
$center_node = array_pop($push_stack);
array_push($visit_stack, $center_node);
//左子樹節點先入$pushstack的棧,確保在$visitstack中先出棧
if ($center_node->child_left != null) array_push($push_stack, $center_node->child_left);
if ($center_node->child_right != null) array_push($push_stack, $center_node->child_right);
}
while (!empty($visit_stack)) {
$center_node = array_pop($visit_stack);
echo $center_node->value . ' ';
}
}
}
//創建二叉樹
$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 = 'a';
$b->value = 'b';
$c->value = 'c';
$d->value = 'd';
$e->value = 'e';
$f->value = 'f';
$g->value = 'g';
$h->value = 'h';
$i->value = 'i';
$a->child_left = $b;
$a->child_right = $c;
$b->child_left = $d;
$b->child_right = $g;
$c->child_left = $e;
$c->child_right = $f;
$d->child_left = $h;
$d->child_right = $i;
//前序遍歷
ergodic::preorder($a); //結果是:a b d h i g c e f
echo '<br/>';
//中序遍歷
ergodic::midorder($a); //結果是: h d i b g a e c f
echo '<br/>';
//后序遍歷
ergodic::endorder($a); //結果是: h i d g b e f c a
s("content_relate");
【php如何實現的二叉樹遍歷(示例)】相關文章:
php如何實現快速排序
09-07
如何用php實現找回密碼
09-21
php如何實現驗證碼
09-07
php弱類型變量是如何實現的
09-03
php代碼如何實現命令行執行
09-30
c++如何實現二叉樹葉子節點個數計算
10-04
php多線程的實現方法
09-12
php如何通過會話控制實現身份驗證
09-22
php如何實現注冊后郵箱驗證和帳號激活
09-15
【本文地址:http://www.zsatt.com/zuowen/2716081.html】