Skip to content

Instantly share code, notes, and snippets.

@tecnom1k3
Created October 17, 2017 03:15
Show Gist options
  • Save tecnom1k3/1d212a7a6e0eb99e2491791ccd68e371 to your computer and use it in GitHub Desktop.
Save tecnom1k3/1d212a7a6e0eb99e2491791ccd68e371 to your computer and use it in GitHub Desktop.
<?php
class TreeNode
{
public $value;
public $left;
public $right;
public function __construct($item)
{
$this->value = $item;
}
public function dump()
{
if ($this->left !== null) {
$this->left->dump();
}
var_dump($this->value);
if ($this->right !== null) {
$this->right->dump();
}
}
}
class Tree
{
protected $root;
public function isEmpty()
{
return $this->root === null;
}
public function insert($item)
{
$node = new TreeNode($item);
if ($this->isEmpty()) {
$this->root = $node;
} else {
$this->insertNode($node, $this->root);
}
}
public function traverse()
{
$this->root->dump();
}
protected function insertNode($node, &$subtree)
{
if ($subtree === null) {
$subtree = $node;
} else {
if ($node->value > $subtree->value) {
$this->insertNode($node, $subtree->right);
} elseif ($node->value < $subtree->value) {
$this->insertNode($node, $subtree->left);
} else {
//no dupes
}
}
}
}
$tree = new Tree;
$tree->insert(3);
$tree->insert(8);
$tree->insert(5);
$tree->insert(4);
$tree->insert(2);
$tree->insert(7);
$tree->insert(6);
$tree->insert(1);
$tree->traverse();
print_r($tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment