看到一位大神写的js的搜索树,自己也按照模式写了一个php的二叉搜索树。
<?php
class node{
public $data;
public $key;
public $left=null;
public $right=null;
function __construct($data=null,$key=null)
{
$this->data=$data;
$this->key=$key;
}
}
class binarysearchtree{
public $root=null;
function insert($data){
$newnode=new node($data);
if ($this->root==null) {
$this->root=$newnode;
return 1;
}
$currentnode=$this->root;
$parentnode=null;
while (true) {
$parentnode = $currentnode;
if ($data < $currentnode->data) {
//当前节点的值 > 目标节点的值
//应该向左插,工作节点移到左节点
$currentnode = $currentnode->left;
if ($currentnode == null) {
//没有左节点,则新节点,直接成为左节点
$parentnode->left = $newnode;
// echo "zuo".$newnode->data;
return 1; //退出循环
}
}
else {
//否则向右插,工作节点移到右节点
$currentnode = $currentnode->right;
if ($currentnode == null) {
$parentnode->right = $newnode;
// echo "you".$parentnode->right->data;
return 1;
}
}
}
}
function maxs() //最大值
{
$p = $this->root; //工作节点
while ($p != null && $p->right != null) {
$p = $p->right;
}
return $p;
}
function mins() //最小值
{
$p = $this->root; //工作节点
while ($p != null && $p->left != null) {
$p = $p->left;
}
return $p;
}
//中序遍历
function inorder($rootnode){
if ($rootnode != null) {
$this->inorder($rootnode->left); //先左节点
print($rootnode->data); //再根节点
$this->inorder($rootnode->right); //再右节点
}
}
function toorder($rootnode){
if ($rootnode != null) {
$this->toorder($rootnode->right); //先左节点
print($rootnode->data); //再根节点
$this->toorder($rootnode->left); //再右节点
}
}
function preorder($rootnode){
if ($rootnode != null) {
print($rootnode->data); //先根
$this->preorder($rootnode->left); //再左节点
$this->preorder($rootnode->right); //再右节点
}
}
function postorder($rootnode){
if ($rootnode != null) {
$this->postorder($rootnode->left); //先左节点
$this->postorder($rootnode->right); //再右节点
print($rootnode->data); //再根节点
}
}
}
header("Content-type: text/html; charset=utf-8");
$btree = new binarysearchtree();
$btree->insert(6);
$btree->insert(3);
$btree->insert(8);
$btree->insert(1);
$btree->insert(4);
$btree->insert(9);
print('中序遍历:');
$btree->inorder($btree->root);
print("<br/>");
print('中序后遍历:');
$btree->toorder($btree->root);
print("<br/>");
print("先序遍历:");
$btree->preorder($btree->root);
print("<br/>");
print("后序遍历:");
$btree->postorder($btree->root);
print("<br/>");
$minnode = $btree->mins();
print("最小节点:".($minnode == null ? "不存在" : $minnode->data));
print("<br/>");
$maxnode = $btree->maxs();
print("最大节点:".($maxnode == null ? "不存在" : $maxnode->data));
?>
注:十万个数排序需要23秒