时间:2021-07-01 10:21:17 帮助过:15人阅读
class Node {
public $data = null;
public $parent = null;
public $left = null;
public $center =null;
public $right = null;
}
function build_cbtree($a) {
$root = new Node();
$root->data = $a[0];
for ($i = 1; $i < count($a); $i++) {
$node = new Node();
$node->data = $a[$i];
insert_node($root, $node);
}
return $root;
}
function insert_node($root, $inode) {
$queue = array();
array_unshift($queue, $root);
while (!empty($queue)) {
$cnode = array_pop($queue);
if ($cnode->left == null) {
$cnode->left = $inode;
$inode->parent = $cnode;
return $root;
} else {
array_unshift($queue, $cnode->left);
}
if ($cnode->center == null) {
$cnode->center = $inode;
$inode->parent = $cnode;
return $root;
} else {
array_unshift($queue, $cnode->center);
}
if ($cnode->right == null) {
$cnode->right = $inode;
$inode->parent = $cnode;
return $root;
} else {
array_unshift($queue, $cnode->right);
}
}
return $root;
}
//广度优先遍历(先遍历一层,再遍历下一层)
function bf_traverse($root) {
$queue = array();
array_unshift($queue, $root);
while (!empty($queue)) {
$cnode = array_pop($queue);
echo $cnode->data . " ";
if ($cnode->left !== null) array_unshift($queue, $cnode->left);
if ($cnode->center !== null) array_unshift($queue, $cnode->center);
if ($cnode->right !== null) array_unshift($queue, $cnode->right);
}
}
$a = array(1,2,3,4,5,6,7,8);
//先把数组变成三叉树
$root = build_cbtree($a);
echo "";";
print_r($root);
echo "
bf_traverse($root);
/*$root数据太多就不打出来了
根据广度优先遍历规则得
1 2 3 4 5 6 7 8
*/
//此时$root就是一个三叉树
//插入9,其实就是重复build_cbtree的方法中for循环的代码
$node1 = new Node();
$node1->data =9;
insert_node($root, $node1);
echo "";";
print_r($root);
echo "
bf_traverse($root);
/*
Node Object
(
[data] => 1
[parent] =>
[left] => Node Object
(
[data] => 2
[parent] => Node Object
*RECURSION*
[left] => Node Object
(
[data] => 5
[parent] => Node Object
*RECURSION*
[left] =>
[center] =>
[right] =>
)
[center] => Node Object
(
[data] => 6
[parent] => Node Object
*RECURSION*
[left] =>