數據結構
- 實現原理:二叉樹
- 操作原理:通過遞歸的方式,對數據進行重排輸出;
<?php
class Node
{
public $leftNode;
public $rightNode;
public $value;
public static $array = [];
public function add($v)
{
if (null === $this->value) {
$this->value = $v;
} else {
if ($v - $this->value < 0) {
if (null == $this->leftNode) {
$this->leftNode = new Node();
}
$this->leftNode->add($v);
} else {
if (null == $this->rightNode) {
$this->rightNode = new Node();
}
$this->rightNode->add($v);
}
}
}
public function values()
{
if (null != $this->leftNode) {
array_merge(self::$array, $this->leftNode->values());
}
array_push(self::$array, $this->value);
if (null != $this->rightNode) {
array_merge(self::$array, $this->rightNode->values());
}
return self::$array;
}
public function execute()
{
$array = [10, 78, 45, 67, 0, 1, 5, 105, 89];
$Node = new Node();
foreach ($array as $vals) {
$Node->add($vals);
}
print_r($Node->values());
}
}