-
Notifications
You must be signed in to change notification settings - Fork 0
Binary Search Tree
PHP Trees has an implementation of a standard binary tree through the BinarySearchTree
include
To create a binary tree simply do the following
$b = new BinarySearchTree();
Which will create an empty tree. You can also optionally pass in a value on construction as the root like so
$b = new BinarySearchTree(5);
Nodes can be inserted in one fo 2 ways, wither one at a time, or as a list
$b = new BinarySearchTree('cat');
$b->insert('dog');
$b->insert('bird', 'fish', 'snake');
The Binary Search Tree comes with the following getters
$b->getRoot(); //returns the root Node (not the value)
$b->getMinValue(); //returns the smallest value in the tree
$b->getMinNode(); //returns the smallest node in the tree
$b->getMaxValue(); //returns the largest value in the tree
$b->getMaxNode(); //returns the largest node in the tree
and also has the search functions
$b->find(5); //returns the node, not the value
$b->hasValue(5);
$b->hasValues('cat', 'dog');
Nodes can also be deleted as well
$b = new BinarySearchTree(5);
$b->insertMultiple(2, 7, 8, 3, 4);
$b->delete($b->find(7)); //note that find is used as the node is needed to delete, incase of duplicate values
The tree is also compatible with PHP's foreach loops, simply access it as you would normally
$b = new BinarySearchTree(10);
$b->insertMultiple(1, 17, 2, 4);
foreach($b as $node) {
echo $b;
}
Which will print out all node values in order, in this case 1, 2, 4, 10, 17
You can also allow for custom comparators in BSTs. This can be done in 2 ways. The result of the following will sort the BST in terms of string length. This can also be used for things like comparing custom objects
// in the constructor
$b = new BinarySearchTree("12345", function($val, $val2) {
return strlen($val) >= strlen($val2);
});
//as a function
$b = new BinarySearchTree();
$b->setComparitor(function($val, $val2) {
return strlen($val) >= strlen($val2);
});