PHP 實現二叉樹排序

數據結構

  • 實現原理:二叉樹
  • 操作原理:通過遞歸的方式,對數據進行重排輸出;
<?php
/**
 *  PHP 實現二叉樹排序
 *  @Author:Victor
 */
class Node
{
    public        $leftNode;
    public        $rightNode;
    public        $value;
    public static $array = [];

    //排序
    public function add($v)
    {
    	//此處必須使用全等於,0才能參與排序
        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);
            }
        }
    }

    /**
     * @return array
     * 獲取節點中的已排序的數據
     */
    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());
        //Array ( [0] => 0 [1] => 1 [2] => 5 [3] => 10 [4] => 45 [5] => 67 [6] => 78 [7] => 89 [8] => 105 )
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章