-
Notifications
You must be signed in to change notification settings - Fork 1
Binary Search Tree
CrimsonNynja edited this page Dec 3, 2019
·
6 revisions
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 or 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