當前位置:才華齋>計算機>php語言>

php如何實現的二叉樹遍歷(示例)

php語言 閱讀(9.43K)

本文主要介紹了php實現的二叉樹遍歷演算法,結合具體例項形式分析了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