PHP 將數群組轉換為完全二叉樹

來源:互聯網
上載者:User
 1 <?php 2     class Node { 3         public $data = null; 4         public $parent = null; 5         public $left = null; 6         public $right = null; 7     } 8  9     #使用數組構造完全二叉樹10     function build_cbtree($a) {11         $root = new Node();12         $root->data = $a[0];13 14         for ($i = 1; $i < count($a); $i++) {15             $node = new Node();16             $node->data = $a[$i];17             insert_node($root, $node);18         }        19 20         return $root;21     }22 23     #插入完全二叉樹節點24     function insert_node($root, $inode) {25         #使用樹的廣度優先遍曆順序取出節點,直到找到第一個左右子節點沒滿的節點,將待插入節點插入節點左邊或右邊26         $queue = array();27         array_unshift($queue, $root);28 29         while (!empty($queue)) {30             $cnode = array_pop($queue);31             if ($cnode->left == null) {32                 $cnode->left = $inode;33                 $inode->parent = $cnode;34                 return $root;35             } else {36                 array_unshift($queue, $cnode->left);                37             }38             if ($cnode->right == null) {39                 $cnode->right = $inode;40                 $inode->parent = $cnode;41                 return $root;42             } else {43                 array_unshift($queue, $cnode->right);44             }45         }46 47         return $root;48     }49 50     #樹的廣度優先遍曆 51     function bf_traverse($root) {52         $queue = array();53         array_unshift($queue, $root);54 55         while (!empty($queue)) {56             $cnode = array_pop($queue);57             echo $cnode->data . " ";58             if ($cnode->left !== null) array_unshift($queue, $cnode->left);59             if ($cnode->right !== null) array_unshift($queue, $cnode->right);60         }61 62         echo "<br>";63     }64 65     $a = array(9, 8, 7, 6, 8, 4, 3, 2, 1);66     $root = build_cbtree($a);67     bf_traverse($root); #廣度優先遍曆68 ?>

9 8 7 6 8 4 3 2 1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.