Created
February 12, 2013 14:29
-
-
Save ackintosh/4770220 to your computer and use it in GitHub Desktop.
Binary tree in PHP
This file contains hidden or 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 | |
class TreeNode | |
{ | |
public $value; | |
public $left; | |
public $right; | |
public function __construct($value) | |
{ | |
$this->value = $value; | |
$this->left = null; | |
$this->right = null; | |
} | |
} | |
class Tree | |
{ | |
private $root; | |
public function contains($v){ | |
return $this->_contains($this->root, $v); | |
} | |
private function _contains($node, $v) | |
{ | |
if ($node === null) return false; | |
if ($node->value === $v) return true; | |
return $v < $node->value ? $this->_contains($node->left, $v) : $this->_contains($node->right, $v); | |
} | |
public function replace(TreeNode $parent, TreeNode $oldNode, TreeNode $newNode) | |
{ | |
if ($parent === null) $this->root = $newNode; | |
if ($parent->left === $oldNode) { | |
$parent->left = $newNode; | |
} elseif ($parent->right === $oldNode) { | |
$parent->right = $newNode; | |
} else { | |
throw new Exception(); | |
} | |
} | |
public function insert($v) | |
{ | |
if ($this->root === null) { | |
$this->root = new TreeNode($v); | |
return $this; | |
} | |
$node = $this->root; | |
while (true) { | |
if ($v <= $node->value) { | |
if ($node->left === null) { | |
$node->left = new TreeNode($v); | |
return $this; | |
} | |
$node = $node->left; | |
} else { | |
if ($node->right === null) { | |
$node->right = new TreeNode($v); | |
return $this; | |
} | |
$node = $node->right; | |
} | |
} | |
} | |
} | |
$t = new Tree(); | |
$t->insert(1)->insert(2); | |
var_dump($t->contains(2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for your effort