Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created February 12, 2013 14:29
Show Gist options
  • Save ackintosh/4770220 to your computer and use it in GitHub Desktop.
Save ackintosh/4770220 to your computer and use it in GitHub Desktop.
Binary tree in PHP
<?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));
@mohamedsst3
Copy link

thanks for your effort

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment