超碰免费人人操|国产视频二区久久艹人人操|欧美激情第一页在线|久热最新无码中文视频|91精品国际成人|亚洲成人精品在线视频青青草|久草免费高清完整在线观看|你懂的AV在线日本黄网页|国产黄色AV日韩女同网|欧美成人色区导航片av

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

時間:2025-12-25 16:56:04 php語言

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

  本文主要介紹了php實現(xiàn)的二叉樹遍歷算法,結(jié)合具體實例形式分析了php針對二叉樹的常用前序、中序及后序遍歷算法實現(xiàn)技巧,需要的朋友可以參考一下!想了解更多相關信息請持續(xù)關注我們應屆畢業(yè)生考試網(wǎng)!

  創(chuàng)建的二叉樹如下圖所示

  php代碼如下所示:

  <?php

  class Node {

  public $value;

  public $child_left;

  public $child_right;

  }

  final class Ergodic {

  /pic/p>

  public static function preOrder($root){

  $stack = array();

  array_push($stack, $root);

  while(!empty($stack)){

  $center_node = array_pop($stack);

  echo $center_node->value . ' ';

  /pic/p>

  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);

  }

  }

  /pic/p>

  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;

  }

  }

  /pic/p>

  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);

  /pic/p>

  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 . ' ';

  }

  }

  }

  /pic/p>

  $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;

  /pic/p>

  Ergodic::preOrder($a); /pic/p>

  echo '<br/>';

  /pic/p>

  Ergodic::midOrder($a); /pic/p>

  echo '<br/>';

  /pic/p>

  Ergodic::endOrder($a); /pic/p>


【php如何實現(xiàn)的二叉樹遍歷(示例)】相關文章:

PHP使用遞歸算法無限遍歷數(shù)組示例09-03

關于php中hashtable實現(xiàn)示例03-02

PHP中多態(tài)如何實現(xiàn)12-26

php如何實現(xiàn)快速排序09-11

如何實現(xiàn)PHP圖片裁剪與縮放01-24

PHP中如何實現(xiàn)crontab代碼07-15

php如何實現(xiàn)驗證碼03-15

如何用PHP實現(xiàn)找回密碼02-03

PHP如何遞歸實現(xiàn)json類10-27