Last active
August 31, 2017 06:30
-
-
Save jaredchu/0b38f1fcea1593eaca182a3897d45b99 to your computer and use it in GitHub Desktop.
Binary Search Tree example in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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