這篇文章將為大家詳細(xì)講解有關(guān)利用php怎么實(shí)現(xiàn)一個(gè)二叉樹遍歷算法,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
成都創(chuàng)新互聯(lián)堅(jiān)信:善待客戶,將會(huì)成為終身客戶。我們能堅(jiān)持多年,是因?yàn)槲覀円恢笨芍档眯刨?。我們從不忽悠初訪客戶,我們用心做好本職工作,不忘初心,方得始終。10多年網(wǎng)站建設(shè)經(jīng)驗(yàn)成都創(chuàng)新互聯(lián)是成都老牌網(wǎng)站營銷服務(wù)商,為您提供成都網(wǎng)站建設(shè)、做網(wǎng)站、網(wǎng)站設(shè)計(jì)、成都h5網(wǎng)站建設(shè)、網(wǎng)站制作、高端網(wǎng)站設(shè)計(jì)、重慶小程序開發(fā)服務(wù),給眾多知名企業(yè)提供過好品質(zhì)的建站服務(wù)。創(chuàng)建的二叉樹如下圖所示
php代碼如下所示:
<?php class Node { public $value; public $child_left; public $child_right; } final class Ergodic { //前序遍歷:先訪問根節(jié)點(diǎn),再遍歷左子樹,最后遍歷右子樹;并且在遍歷左右子樹時(shí),仍需先遍歷根節(jié)點(diǎn),然后訪問左子樹,最后遍歷右子樹 public static function preOrder($root){ $stack = array(); array_push($stack, $root); while(!empty($stack)){ $center_node = array_pop($stack); echo $center_node->value . ' '; //先把右子樹節(jié)點(diǎn)入棧,以確保左子樹節(jié)點(diǎn)先出棧 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); } } //中序遍歷:先遍歷左子樹、然后訪問根節(jié)點(diǎn),最后遍歷右子樹;并且在遍歷左右子樹的時(shí)候。仍然是先遍歷左子樹,然后訪問根節(jié)點(diǎn),最后遍歷右子樹 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; } } //后序遍歷:先遍歷左子樹,然后遍歷右子樹,最后訪問根節(jié)點(diǎn);同樣,在遍歷左右子樹的時(shí)候同樣要先遍歷左子樹,然后遍歷右子樹,最后訪問根節(jié)點(diǎn) 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); //左子樹節(jié)點(diǎn)先入$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 . ' '; } } } //創(chuàng)建二叉樹 $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); //結(jié)果是:A B D H I G C E F echo '
'; //中序遍歷 Ergodic::midOrder($a); //結(jié)果是: H D I B G A E C F echo '
'; //后序遍歷 Ergodic::endOrder($a); //結(jié)果是: H I D G B E F C A