使用PHP实现二叉树
<?php
class tree
{
public $value ;
public $left ;
public $right ;
public function __construct ( $value = null ) {
$this - > value = $value ;
}
public function add ( $tree , $value ) {
if ( $tree == null ) {
return new self ( $value ) ;
}
if ( $value < $tree - > value ) {
$tree - > left = $this - > add ( $tree - > left , $value ) ;
} else {
$tree - > right = $this - > add ( $tree - > right , $value ) ;
}
return $tree ;
}
public function sort ( $values ) {
$tree = null ;
foreach ( $values as $value ) {
$tree = $this - > add ( $tree , $value ) ;
}
return $this - > appendValues ( [ ] , $tree ) ;
}
public function appendValues ( $values , $tree ) {
if ( $tree != null ) {
$values = $this - > appendValues ( $values , $tree - > left ) ;
array_push ( $values , $tree - > value ) ;
$values = $this - > appendValues ( $values , $tree - > right ) ;
}
return $values ;
}
}