Skip to content

Instantly share code, notes, and snippets.

@greydnls
Last active August 29, 2015 14:11
Show Gist options
  • Save greydnls/4a6977f8204a736864cb to your computer and use it in GitHub Desktop.
Save greydnls/4a6977f8204a736864cb to your computer and use it in GitHub Desktop.
Binary Search Tree Implementation
<?php
/**
* Created by PhpStorm.
* User: kayladnls
* Date: 12/17/14
* Time: 5:06 PM
*/
class BinarySearchTree
{
public $left = NULL;
public $right = NULL;
public $value = NULL;
private function __construct($value)
{
$this->value = $value;
}
public static function create($value = null)
{
return new static($value);
}
public function insert($value)
{
if ($value == $this->value) return;
if ($this->value == NULL)
{
$this->value = $value;
}
else if ($value < $this->value)
{
if ($this->left == NULL)
{
$this->left = BinarySearchTree::create($value, $this);
}
else
{
$this->left->insert($value);
}
}
else
{
if ($this->right == null)
{
$this->right = BinarySearchTree::create($value, $this);
}
else
{
$this->right->insert($value);
}
}
}
public function applyDelete()
{
$children = $this->countChildren();
switch ($children)
{
case 0:
return null;
break;
case 1:
return ($this->left != NULL) ? $this->left : $this->right;
break;
case 2:
$this->value = $this->right->pop();
return $this;
break;
}
}
public function getMinValueDelete()
{
if ($this->value == NULL) return;
if ($this->left !== NULL && $this->left->hasChildren())
{
return $this->left->getMin();
}
else if ($this->left !== NULL)
{
$min = $this->left->value;
$this->left = NULL;
return $min;
}
else if ($this->right !== NULL && $this->right->hasChildren())
{
return $this->right->getMin();
}
else
{
$min = $this->right->value;
$this->right = NULL;
return $min;
}
}
public function delete($value)
{
if ($value == $this->left->value)
{
$this->left = $this->left->applyDelete();
}
else if ($value == $this->right->value)
{
$this->right = $this->right->applyDelete();
}
else if ($value < $this->value)
{
$this->left->delete($value);
}
else
{
$this->right->delete($value);
}
}
public function hasChildren()
{
return $this->left !== NULL || $this->right !== NULL;
}
public function search($value)
{
if ($this->value == $value) return $this->value;
if ($value < $this->value && $this->left != NULL)
{
return $this->left->search($value);
}
else if ($this->right != NULL)
{
return $this->right->search($value);
}
}
public function countChildren()
{
$count = 0;
if ($this->left !== null) $count++;
if ($this->right !== null) $count++;
return $count;
}
function __toString()
{
$output = "";
$output .= $this->value;
$output .= "\n";
$output .= $this->left;
$output .= $this->right;
return $output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment