Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Created November 10, 2019 23:38
Show Gist options
  • Save adrianosferreira/713ced11d1f367289f36ab4ee1223552 to your computer and use it in GitHub Desktop.
Save adrianosferreira/713ced11d1f367289f36ab4ee1223552 to your computer and use it in GitHub Desktop.
Binary Search Tree with PHP
<?php
/**
* Created by PhpStorm.
* User: adriano
* Date: 10/11/19
* Time: 20:17
*/
class Node {
private $left;
private $right;
private $data;
public function __construct( $data ) {
$this->data = $data;
}
public function setLeft( Node $node ) {
$this->left = $node;
}
public function getLeft() {
return $this->left;
}
public function setRight( Node $node ) {
$this->right = $node;
}
public function getRight() {
return $this->right;
}
public function getData() {
return $this->data;
}
}
class binarySearchTree {
private $root;
public function insert( $value ) {
$node = new Node( $value );
if ( ! $this->root ) {
$this->root = $node;
return;
}
$this->insertNode( $this->root, $node );
}
public function search( $value ) {
return $this->searchNode( $this->root, $value );
}
private function searchNode( $currentNode, $value ) {
if ( $currentNode->getData() === $value ) {
return true;
}
if ( $value < $currentNode->getData() && $currentNode->getLeft() ) {
return $this->searchNode( $currentNode->getLeft(), $value );
}
if ( $value > $currentNode->getData() && $currentNode->getRight() ) {
return $this->searchNode( $currentNode->getRight(), $value );
}
return false;
}
private function insertNode( $currentNode, $node ) {
if ( $node->getData() < $currentNode->getData() ) {
if ( ! $currentNode->getLeft() ) {
$currentNode->setLeft( $node );
}
$this->insertNode( $currentNode->getLeft(), $node );
}
if ( $node->getData() > $currentNode->getData() ) {
if ( ! $currentNode->getRight() ) {
$currentNode->setRight( $node );
}
$this->insertNode( $currentNode->getRight(), $node );
}
}
}
$binarySearchTree = new binarySearchTree();
$binarySearchTree->insert( 10 );
$binarySearchTree->insert( 6 );
$binarySearchTree->insert( 18 );
$binarySearchTree->insert( 4 );
$binarySearchTree->insert( 8 );
$binarySearchTree->insert( 15 );
$binarySearchTree->insert( 21 );
$result = $binarySearchTree->search( 50 );
$test = 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment