二叉查詢樹屬於動態查詢表,在查詢時可插入資料或是刪除資料。
基礎基於二叉樹,只不過它的特點是左子樹結點的值永遠小於右子樹結點的值。
二叉樹:由左右子樹構成的二叉樹。
分類:斜樹【即只有左或是右子樹】,滿二叉樹【結點層次一致】,完全二叉樹。
遍歷演算法:【前序,中序,後序,層序】遍歷演算法
本節基於資料動態構建一個二叉排序數,並完成查詢樹中結點和刪除某個結點功能!!!,用於對樹進行建立,刪除,查詢,展示功能。
<?php
/**
* Created by PhpStorm.
* User: 1655664358@qq.com
* Date: 2019/6/1
* Time: 13:04
*/
/**
* 樹結點
* Class Tree
*/
class Tree
{
public $data;
public $LChild;
public $RChild;
}
/**
* 二叉查詢樹【二叉排序樹】
* @param $tree
* @param $data
* @param $f
* @param $temp
* @return bool
*/
function searchBSTree(&$tree,$data,$f,&$temp)
{
if (is_null($tree)){
$temp = $f;
return false;
}
else if ($data==$tree->data){
$temp = $tree;
return true;
}
else if ($data<$tree->data){
return searchBSTree($tree->LChild,$data,$tree,$temp);
}else{
return searchBSTree($tree->RChild,$data,$tree,$temp);
}
}
/**
* 構建二叉排序樹
* @param $tree
* @param $data
*/
function createBSTree(&$tree,$data)
{
$temp = new Tree();
if (!searchBSTree($tree,$data,null,$temp)){
$obj = new Tree();
$obj->data = $data;
$obj->LChild=$obj->RChild=null;
if (is_null($temp)){
$tree=$obj;
}
elseif($data<$temp->data){
$temp->LChild = $obj;
}else{
$temp->RChild = $obj;
}
}
}
/**
* 刪除二叉排序樹某個結點
* @param $tree
* @return bool
*/
function removeBST(&$tree)
{
if (is_null($tree->RChild)&&is_null($tree->LChild)){
$tree=null;
return true;
}
else if (is_null($tree->LChild)){
$tree = $tree->RChild;
}else if (is_null($tree->RChild)){
$tree = $tree->LChild;
}else{
$temp = $tree;
/** @var Tree $left */
$left = $tree->LChild;
while ($left->RChild){
$temp = $left;
$left = $left->RChild;
}
$tree->data = $left->data;//欲刪除結點替換操作
if ($temp!=$tree){
$temp->RChild=$left->LChild;//右子樹替換,因為右子樹的資料已經替換為刪除的結點
}else{
$tree->LChild=$left->LChild;//沒有右子樹的情況下,直接替換左子樹
}
}
}
function deleteBSTree(&$tree,$data)
{
if (is_null($tree)){
return false;
}
elseif($data==$tree->data){
removeBST($tree);
return true;
}else if($data<$tree->data){
return deleteBSTree($tree->LChild,$data);
}else{
return deleteBSTree($tree->RChild,$data);
}
}
/**
* 前【先】序遍歷
* @param $tree
*/
function displayTree($tree)
{
if (!is_null($tree))
{
fwrite(STDOUT,$tree->data."\n",10);
displayTree($tree->LChild);
displayTree($tree->RChild);
}
}
(function(){
$data = [50,25,30,12,6,20,18,15,26,27,28,29];
$tree = null;
for ($i=0;$i<12;$i++){
createBSTree($tree,$data[$i]);
}
displayTree($tree);
deleteBSTree($tree,50);
fwrite(STDOUT,"************************\n",512);
displayTree($tree);
})();
演算法廢腦子,自己擼碼看看吧^_^
基礎依賴於二叉樹