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 '
';//中序遍歷
ergodic::midorder($a); //結果是: h d i b g a e c f
echo '
';//後序遍歷
ergodic::endorder($a); //結果是: h i d g b e f c a
PHP實現完全二叉樹
若設二叉樹的深度為h,除第 h 層外,其它各層 1 h 1 的結點數都達到最大個數,第 h 層所有的結點都連續集中在最左邊,這就是完全二叉樹。php 實現 暫時實現新增節點 層次遍歷節點,刪除節點後續更新 class node 找到空節點 function findempytnode node,pa...
PHP遍歷二叉樹
遍歷二叉樹,這個相對比較複雜。二叉樹的便利,主要有兩種,一種是廣度優先遍歷,一種是深度優先遍歷。什麼是廣度優先遍歷?就是根節點進入,水平一行一行的便利。什麼是深度優先遍歷呢?就是根節點進入,然後按照乙個固定的規律,一直向下走,乙個方向的子樹遍歷之後再遍歷另乙個方向的子樹。深度優先遍歷,主要有三種順序...
二叉樹之 二叉樹深度
二叉樹深度 獲取最大深度 public static int getmaxdepth treenode root 二叉樹寬度 使用佇列,層次遍歷二叉樹。在上一層遍歷完成後,下一層的所有節點已經放到佇列中,此時佇列中的元素個數就是下一層的寬度。以此類推,依次遍歷下一層即可求出二叉樹的最大寬度 獲取最大...