By applying some sort logic between the nodes, the binary tree provides an excellent way to organize. For each node, the element that satisfies all the specific criteria is located on the left node and its child nodes. When inserting new elements, we need to start with the first node (the root node) of the tree, determine which side of the node it belongs to, and then find the right place along this side, and similarly, when reading the data, we only need to use the sequential traversal method to traverse the binary tree.
Copy Code code as follows:
<?php
Ob_start ();
Here we are need to include the binary tree class
Class Binary_tree_node () {
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 we tree:
Public $tree;
We need a method that would allow for inserts that automatically place
themselves in the proper
Public Function Insert ($val) {
Handle:
if (!) ( Isset ($this->tree))) {
$this->tree = new Binary_tree_node ($val);
} else {
In all other cases:
Start A pointer that looks in 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 is the sorted values of this tree.
All it entails are using the In-order traversal which would 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 numbers inserting them as we go:
for ($i = 0; $i < $i + +) {
$sort _as_you_go->insert (rand (1,100));
}
Now Echo is out, using in-order traversal, and it'll 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> ';
?>