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