您好,欢迎访问一九零五行业门户网

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

在节点之间再应用一些排序逻辑,二叉树就能提供出色的组织方式。对于每个节点,都让满足所有特定条件的元素都位于左节点及其子节点。在插入新元素时,我们需要从树的第一个节 点(根节点)开始,判断它属于哪一侧的节点,然后沿着这一侧找到恰当的位置,类似地,在读取数据时,只需要使用按序遍历方法来遍历二叉树。
复制代码 代码如下:
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 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     $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 '', implode(', ', $sort_as_you_go->returnsorted()), '
';
?>
http://www.bkjia.com/phpjc/327866.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/327866.htmltecharticle在节点之间再应用一些排序逻辑,二叉树就能提供出色的组织方式。对于每个节点,都让满足所有特定条件的元素都位于左节点及其子节点...
其它类似信息

推荐信息