插入是基于查找的过程,如果找不到,通过最后一个被查找的节点判断,如果查找值小于该节点,将查找值赋予
该节点的左孩子,否则赋予该节点的右孩子。
代码如下:
<?php
class BinaryTree
{
public $data;
public $lChild;
public $rChild;
public function __construct($data, $lChild = null, $rChild = null)
{
$this->data = $data;
$this->lChild = $lChild;
$this->rChild = $rChild;
}
}
$b37 = new BinaryTree(37);
$b35 = new BinaryTree(35, null, $b37);
$b51 = new BinaryTree(51);
$b47 = new BinaryTree(47, $b35, $b51);
$b58 = new BinaryTree(58, $b47);
$b93 = new BinaryTree(93);
$b99 = new BinaryTree(99, $b93);
$b73 = new BinaryTree(73);
$b88 = new BinaryTree(88, $b73, $b99);
$binaryTree = new BinaryTree(62, $b58, $b88);
$tmp = null;
function searchBst($binaryTree, $key)
{
if (is_null($binaryTree)) {
return false;
} else {
global $tmp;
$tmp = $binaryTree;
}
if ($binaryTree->data == $key) {
return true;
} else if ($key < $binaryTree->data) {
return searchBst($binaryTree->lChild, $key);
} else {
return searchBst($binaryTree->rChild, $key);
}
}
// $res = searchBst($binaryTree, 99);
// print_r($res);echo "\n";
// print_r($tmp);echo "\n";
//二叉排序树插入操作
function InsertBst(&$binaryTree, $key)
{
global $tmp;
if (!searchBst($binaryTree, $key)) {
$data = new BinaryTree($key);
$data->lChild = $data->rChild = null;
if (!$tmp) {
$binaryTree = $data;
} else if ($key < $tmp->data) {
$tmp->lChild = $data;
} else {
$tmp->rChild = $data;
}
return true;
}
return false;
}
// $res = InsertBst($binaryTree, 93);
// print_r($res);echo "\n";
// print_r($tmp);echo "\n";
// print_r($binaryTree);echo "\n";
$binaryTree = null;
$tree = array(62,88,58,47,35,73,51,99,37,93);
foreach ($tree as $key => $value) {
# code...
InsertBst($binaryTree, $value);
}
print_r($binaryTree);echo "\n";