Skip to content

Instantly share code, notes, and snippets.

@jaredchu
Last active August 31, 2017 06:30
Show Gist options
  • Save jaredchu/0b38f1fcea1593eaca182a3897d45b99 to your computer and use it in GitHub Desktop.
Save jaredchu/0b38f1fcea1593eaca182a3897d45b99 to your computer and use it in GitHub Desktop.
Binary Search Tree example in PHP
<?php
/**
* Created by PhpStorm.
* User: jaredchu
* Date: 31/08/2017
* Time: 11:40
*/
class Node
{
/**
* @var Node
*/
public $left;
/**
* @var integer
*/
public $value;
/**
* @var Node
*/
public $right;
/**
* Node constructor.
* @param int $value
*/
public function __construct($value)
{
$this->value = $value;
}
public function insert($value)
{
switch ($value <=> $this->value) {
case -1:
return $this->insertLeft($value);
case 1:
return $this->insertRight($value);
default:
return false;
}
}
protected function insertLeft($value)
{
if ($this->left) {
$this->left->insert($value);
} else {
$this->left = new Node($value);
}
return $this->left;
}
protected function insertRight($value)
{
if ($this->right) {
$this->right->insert($value);
} else {
$this->right = new Node($value);
}
return $this->right;
}
protected function hasChild()
{
return !is_null($this->left) || !is_null($this->right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment