欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP Class&Object -- PHP 自排序二叉树的深入解析

程序员文章站 2022-07-25 20:38:41
在节点之间再应用一些排序逻辑,二叉树就能提供出色的组织方式。对于每个节点,都让满足所有特定条件的元素都位于左节点及其子节点。在插入新元素时,我们需要从树的第一个节 点(根节...
在节点之间再应用一些排序逻辑,二叉树就能提供出色的组织方式。对于每个节点,都让满足所有特定条件的元素都位于左节点及其子节点。在插入新元素时,我们需要从树的第一个节 点(根节点)开始,判断它属于哪一侧的节点,然后沿着这一侧找到恰当的位置,类似地,在读取数据时,只需要使用按序遍历方法来遍历二叉树。
复制代码 代码如下:

<?php
ob_start();
// here we need to include the binary tree class
class binary_tree_node() {
   // you can find the details at
}
ob_end_clean();
// define a class to implement self sorting binary tree
class sorting_tree {
    // define the variable to hold our tree:
    public $tree;
    // we need a method that will allow for inserts that automatically place
    // themselves in the proper order in the tree
    public function insert($val) {
        // handle the first case:
        if (!(isset($this->tree))) {
            $this->tree = new binary_tree_node($val);
        } else {
            // in all other cases:
            // start a pointer that looks at the current tree top:
            $pointer = $this->tree;
            // iteratively search the tree for the right place:
            for(;;) {
                // if this value is less than, or equal to the current data:
                if ($val <= $pointer->data) {
                    // we are looking to the left ... if the child exists:
                    if ($pointer->left) {
                        // traverse deeper:
                        $pointer = $pointer->left;
                    } else {
                        // found the new spot: insert the new element here:
                        $pointer->left = new binary_tree_node($val);
                        break;
                    }
                } else {
                    // we are looking to the right ... if the child exists:
                    if ($pointer->right) {
                        // traverse deeper:
                        $pointer = $pointer->right;
                    } else {
                        // found the new spot: insert the new element here:
                        $pointer->right = new binary_tree_node($val);
                        break;
                    }
                }
            }
        }
    }

    // now create a method to return the sorted values of this tree.
    // all it entails is using the in-order traversal, which will now
    // give us the proper sorted order.
    public function returnsorted() {
        return $this->tree->traverseinorder();
    }
}
// declare a new sorting tree:
$sort_as_you_go = new sorting_tree();
// let's randomly create 20 numbers, inserting them as we go:
for ($i = 0; $i < 20; $i++) {
    $sort_as_you_go->insert(rand(1,100));
}
// now echo the tree out, using in-order traversal, and it will be sorted:
// example: 1, 2, 11, 18, 22, 26, 32, 32, 34, 43, 46, 47, 47, 53, 60, 71,
//   75, 84, 86, 90
echo '<p>', implode(', ', $sort_as_you_go->returnsorted()), '</p>';
?>