找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 622|回复: 0
打印 上一主题 下一主题

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

[复制链接]

2647

主题

2647

帖子

7881

积分

论坛元老

Rank: 8Rank: 8

积分
7881
跳转到指定楼层
楼主
发表于 2018-2-14 08:16:35 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

            在节点之间再应用一些排序逻辑,二叉树就能提供出色的组织方式。对于每个节点,都让满足所有特定条件的元素都位于左节点及其子节点。在插入新元素时,我们需要从树的第一个节 点(根节点)开始,判断它属于哪一侧的节点,然后沿着这一侧找到恰当的位置,类似地,在读取数据时,只需要使用按序遍历方法来遍历二叉树。
[U]复制代码[/U] 代码如下:
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 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()), '
';
?>
            
            
您可能感兴趣的文章:
  • php FLEA中二叉树数组的遍历输出
  • PHP Class&Object -- 解析PHP实现二叉树
  • PHP实现二叉树的深度优先与广度优先遍历方法
  • PHP实现的线索二叉树及二叉树遍历方法详解
  • php实现的二叉树遍历算法示例
  • PHP构造二叉树算法示例
  • PHP完全二叉树定义与实现方法示例
  • PHP实现绘制二叉树图形显示功能详解【包括二叉搜索树、平衡树及红黑树】
  • PHP实现判断二叉树是否对称的方法
  • PHP基于非递归算法实现先序、中序及后序遍历二叉树操作示例
  • PHP实现按之字形顺序打印二叉树的方法
            
  • 分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    用户反馈
    客户端