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

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


代码如下:

<?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>';
?>

(0)

相关推荐

  • PHP构造二叉树算法示例

    树(Tree)在数据结构还是很重要的,这里表示二叉树用括号表示法表示.先写一个二叉树节点类: // 二叉树节点 class BTNode { public $data; public $lchild = NULL; public $rchild = NULL; public function __construct($data) { $this->data = $data; } } 然后构造二叉树: function CreateBTNode(&$root,string $str) { $s

  • PHP字典树(Trie树)定义与实现方法示例

    本文实例讲述了PHP字典树(Trie树)定义与实现方法.分享给大家供大家参考,具体如下: Trie树的概念(百度的解释):字典树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种.典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计.它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高. 我的理解是用来做字符串搜索的,每个节点只包含一个字符,比如录入单词"world",则树的结构

  • PHP递归实现层级树状展开

    本文实例为大家分享了PHP递归实现层级树状展开的主要代码,供大家参考,具体内容如下 效果图: 实现代码: <?php $db = mysql_connect('localhost', 'root', 'root') or die('Can\'t connect to database'); mysql_select_db('test') or die('Can\'t find database : test'); $result = mysql_query('select id, fid, na

  • PHP树的深度编历生成迷宫及A*自动寻路算法实例分析

    本文实例讲述了PHP树的深度编历生成迷宫及A*自动寻路算法.分享给大家供大家参考.具体分析如下: 有一同事推荐了三思的迷宫算法,看了感觉还不错,就转成php 三思的迷宫算法是采用树的深度遍历原理,这样生成的迷宫相当的细,而且死胡同数量相对较少! 任意两点之间都存在唯一的一条通路. 至于A*寻路算法是最大众化的一全自动寻路算法 废话不多说,贴上带代码 迷宫生成类: 复制代码 代码如下: class Maze{     // Maze Create     private $_w;     priv

  • PHP实现二叉树的深度优先与广度优先遍历方法

    本文实例讲述了PHP实现二叉树的深度优先与广度优先遍历方法.分享给大家供大家参考.具体如下: #二叉树的广度优先遍历 #使用一个队列实现 class Node { public $data = null; public $left = null; public $right = null; } #@param $btree 二叉树根节点 function breadth_first_traverse($btree) { $traverse_data = array(); $queue = arr

  • PHP树-不需要递归的实现方法

    PHP树-不需要递归的实现方法 /** * 创建父节点树形数组 * 参数 * $ar 数组,邻接列表方式组织的数据 * $id 数组中作为主键的下标或关联键名 * $pid 数组中作为父键的下标或关联键名 * 返回 多维数组 **/ function find_parent($ar, $id='id', $pid='pid') { foreach($ar as $v) $t[$v[$id]] = $v; foreach ($t as $k => $item){ if( $item[$pid] )

  • php FLEA中二叉树数组的遍历输出

    但是要怎样遍历这个方法产生的二叉树数组呢?以下是我的做法: 复制代码 代码如下: <?php function preTree($cat){ foreach ($cat as $c){ ?> <p><a href="http://<?=$c['poper_site']?>"><?=$c['poper']?></a>:<?=t($c['content'])?></p> <?php if(

  • php实现的二叉树遍历算法示例

    本文实例讲述了php实现的二叉树遍历算法.分享给大家供大家参考,具体如下: 今天使用php来实现二叉树的遍历 创建的二叉树如下图所示 php代码如下所示: <?php class Node { public $value; public $child_left; public $child_right; } final class Ergodic { //前序遍历:先访问根节点,再遍历左子树,最后遍历右子树:并且在遍历左右子树时,仍需先遍历根节点,然后访问左子树,最后遍历右子树 public s

  • PHP生成树的方法

    本文实例讲述了PHP生成树的方法.分享给大家供大家参考.具体如下: 这个类不是我写的 只添加了getAll()函数 php生成一个树,可以用于产品分类 不知道遍历写的是否优化,如果你有请分享一下吧 -.-! 运行效果如下图所示: 实现代码如下: <?php class Tree { public $data=array(); public $cateArray=array(); public $res=array(); function Tree() { } function setNode (

  • php遍历树的常用方法汇总

    本文实例讲述了php遍历树的常用方法.分享给大家供大家参考.具体如下: 一.递归的深度优先的算法: <?php define('DS', DIRECTORY_SEPARATOR); function rec_list_files($from = '.') { if(!is_dir($from)) { return array(); } $files = array(); if($dh = opendir($from)) { while(false !== ($file = readdir($dh

  • PHP实现的线索二叉树及二叉树遍历方法详解

    本文实例讲述了PHP实现的线索二叉树及二叉树遍历方法.分享给大家供大家参考,具体如下: <?php require 'biTree.php'; $str = 'ko#be8#tr####acy#####'; $tree = new BiTree($str); $tree->createThreadTree(); echo $tree->threadList() . "\n";从第一个结点开始遍历线索二叉树 echo $tree->threadListReserv

  • PHP Class&Object -- 解析PHP实现二叉树

    二叉树及其变体是数据结构家族里的重要组成部分.最为链表的一种变体,二叉树最适合处理需要一特定次序快速组织和检索的数据. 复制代码 代码如下: <?php// Define a class to implement a binary treeclass Binary_Tree_Node {    // Define the variable to hold our data:    public $data;    // And a variable to hold the left and ri

随机推荐