Skip to content

Binary Search Tree

CrimsonNynja edited this page Nov 11, 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

Clone this wiki locally