PHP 二叉樹的深度優先與廣度優先遍曆

來源:互聯網
上載者:User
 1 <?php 2      #二叉樹的廣度優先遍曆 3      #使用一個隊列實現 4   5      class Node { 6          public $data = null; 7          public $left = null; 8          public $right = null; 9      }10  11      #@param $btree 二叉樹根節點12      function breadth_first_traverse($btree) {13          $traverse_data = array();14          $queue = array();15          array_unshift($queue, $btree); #根節點入隊16          17          while (!empty($queue)) { #持續輸出節點,直到隊列為空白18              $cnode = array_pop($queue); #隊尾元素出隊19              $traverse_data[] = $cnode->data;20  21              #左節點先入隊,然後右節點入隊22              if ($cnode->left != null) array_unshift($queue, $cnode->left);23              if ($cnode->right != null) array_unshift($queue, $cnode->right);24          }25  26          return $traverse_data;27      }28 29      #深度優先遍曆,使用一個棧實現30      function depth_first_traverse($btree) {31         $traverse_data = array();32         $stack = array();33         array_push($stack, $btree);34 35         while (!empty($stack)) {36             $cnode = array_pop($stack);37             $traverse_data[] = $cnode->data;38 39             if ($cnode->right != null) array_push($stack, $cnode->right);40             if ($cnode->left != null) array_push($stack, $cnode->left);41         }42 43         return $traverse_data;44      }45  46      $root = new Node();47      $node1 = new Node();48      $node2 = new Node();49      $node3 = new Node();50      $node4 = new Node();51      $node5 = new Node();52      $node6 = new Node();53  54      $root->data = 1;55      $node1->data = 2;56      $node2->data = 3;57      $node3->data = 4;58      $node4->data = 5;59      $node5->data = 6;60      $node6->data = 7;61  62      $root->left = $node1;63      $root->right = $node2;64      $node1->left = $node3;65      $node1->right = $node4;66      $node2->left = $node5;67      $node2->right = $node6;68  69      $traverse = breadth_first_traverse($root);70      print_r($traverse);71      echo "<br>";72      $traverse = depth_first_traverse($root);73      print_r($traverse);74  ?>

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 ) 
Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 [4] => 3 [5] => 6 [6] => 7 )

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.