删除节点有三种情况:
1.叶子节点 2.仅有左或右子树的节点 3.左右子树都有的节点
<?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, 103);
// print_r($res);echo "\n";
// print_r($tmp);echo "\n";
print_r($binaryTree);echo "\n";
//-----------------------------------------------
function Delete(BinaryTree $biTree) {
if ($biTree->lChild === null) {
$biTree = $biTree->rChild;
} else if ($biTree->rChild === null) {
$biTree = $biTree->lChild;
} else {
//找到要删除的节点的最右节点
$changeNode = $biTree;
$deleteLeftNode = $biTree->lChild;
while (!is_null($deleteLeftNode->rChild)) {
$changeNode = $deleteLeftNode;
$deleteLeftNode = $deleteLeftNode->rChild;
}
$biTree->data = $deleteLeftNode->data;
if ($biTree == $changeNode) {
$changeNode->lChild = $deleteLeftNode->lChild;
} else {
$changeNode->rChild = $deleteLeftNode->lChild;
}
}
}
function DeleteBst($biTree, $key) {
if (is_null($biTree)) {
return false;
}
if ($biTree->data == $key) {
return Delete($biTree);
} else if ($biTree->data < $key) {
return DeleteBst($biTree->rChild, $key);
} else {
return DeleteBst($biTree->lChild, $key);
}
}
DeleteBst($binaryTree, 47);
print_r($binaryTree);
//-----------------------------------------------
// $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";