树的节点存储的是学生的信息
节点的比较以信息中的学号为准;
<?php
class Node{
private $num;//学生学号
private $name;//学生姓名
private $scoreChinese;//学生语文成绩
private $scoreMath;//数学成绩
private $scoreEnglish;//英语成绩
private $left;
private $right;
public function __construct(){
$this->left = null;
$this->right = null;
}
public function __set($key,$value){
$this->$key = $value;
}
public function __get($key){
if(isset($this->$key)){
return $this->$key;
}
}
}
class Tree{
private $top;//树顶节点
public function __construct($array){
//生成树
$falses = $this->makeTree($array);
$this->readTree();
}
public function makeTree($array){
if(empty($array)){
$this->top = null;
return;
}
//选择树顶节点
$temp = $array[floor(count($array)/2)];
$this->top->num = $temp['num'];
$this->top->name = $temp['name'];
$this->top->scoreChinese = $temp['scoreChinese'];
$this->top->scoreMath = $temp['scoreMath'];
$this->top->scoreEnglish = $temp['scoreEnglish'];
$this->top->left = null;
$this->top->right = null;
unset($array[floor(count($array)/2)]);
$false = 0;//建树失败的节点
foreach($array as $value){
if(false == $this->insert($value)){
$false++;
}
}
}
/**
插入节点
*/
public function insert($info){
$aNode = new Node();
$aNode->num = $info['num'];
$aNode->name = $info['name'];
$aNode->scoreChinese = $info['scoreChinese'];
$aNode->scoreMath = $info['scoreMath'];
$aNode->scoreEnglish = $info['scoreEnglish'];
$aNode->left = null;
$aNode->right = null;
if(null == $this->top){
$this->top = $aNode;
return;
}
$nowNode = $this->top;
while(true){
if($nowNode->num == $aNode->num){
return false;
}elseif($nowNode->num>$aNode->num && null == $nowNode->left){
$nowNode->left = $aNode;
return true;
}elseif($nowNode->num<$aNode->num && null == $nowNode->right){
$nowNode->right = $aNode;
return true;
}elseif($nowNode->num>$aNode->num && $nowNode->left != null){
$nowNode = $nowNode->left;
}elseif($nowNode->num<$aNode->num && $nowNode->right != null){
$nowNode = $nowNode->right;
}
}
}
/**
查询节点
*/
public function search($num){
$nowNode = $this->top;
while(true){
if($nowNode->num == $num){
return $nowNode;
}elseif($nowNode->num>$num && null == $nowNode->left){
return null;
}elseif($nowNode->num<$num && null == $nowNode->right){
return null;
}elseif($nowNode->num>$num && $nowNode->left!=null){
$nowNode = $nowNode->left;
}elseif($nowNode->num<$num && $nowNode->right!=null){
$nowNode = $nowNode->right;
}
}
}
/**
树是否为空
*/
public function isEmpty(){
if(is_null($this->top)){
return true;
}else{
return false;
}
}
/**
中序便利树
*/
public function readTree(){
$result = array();
$this->read($this->top,$result);
return $result;
}
private function read($nowNode,&$result){
if(null != $nowNode->left){
$this->read($nowNode->left,$result);
}
array_push($result,$nowNode);
if(null != $nowNode->right){
$this->read($nowNode->right,$result);
}
}
}
?>