您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關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>';
?>
關于“PHP如何實現自排序二叉樹”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。