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