Skip to content

Instantly share code, notes, and snippets.

@Zetzumarshen
Last active April 21, 2016 23:22
Show Gist options
  • Save Zetzumarshen/3771df5cb6211bf89419708e0d2f7ee3 to your computer and use it in GitHub Desktop.
Save Zetzumarshen/3771df5cb6211bf89419708e0d2f7ee3 to your computer and use it in GitHub Desktop.
<?php
class GenericTree {
public $root;
function __construct() {
$this->root = new Node();
}
public function insert(Array $indexes, $value) {
$newNode = new Node($value);
$currentNode = $this->root;
$this->_insert($currentNode, $newNode, $indexes);
}
private function _insert(Node $currentNode, Node $newNode, Array $indexes) {
if (sizeof($indexes) > 0) {
if ($currentNode->getSizeOfChildren() === 0) {
throw new Exception('insert failed, $indexes level out of bounds');
}
$index = array_shift($indexes);
$currentNode = $currentNode->getChild($index);
$this->_insert($currentNode, $newNode, $indexes);
} else {
$currentNode->addChild($newNode);
}
}
public function inOrder(Callable $preOp, Callable $inOp, Callable $postOp) {
$this->_inOrder($this->root, $preOp, $inOp, $postOp);
}
private function _inOrder(Node $n, Callable $preOp, Callable $inOp, Callable $postOp) {
try {
$preOp();
for($index = 0; $index < $n->getSizeOfChildren(); $index ++) {
$nodeValue = $n->getChild($index)->value;
$inOp($nodeValue);
$this->_inOrder($n->getChild($index), $preOp, $inOp, $postOp);
}
$postOp();
} catch ( Exception $e ) {
$msg = $e->message();
throw new Exception("inOrder failed \n $msg");
}
}
}
class Node {
private $children = array ();
public $value = NULL;
function __construct($value = NULL) {
$this->value = $value;
}
public function getSizeOfChildren() {
return sizeof($this->children);
}
public function getChild($index) {
if ($index < sizeof($this->children)) {
return $this->children [$index];
} else {
throw new Exception('getChild failed, $index out of Bounds');
}
}
public function setChild($index, $value) {
if ($index < sizeof($this->children)) {
$this->children [$index] = $value;
} else {
throw new Exception('setChild failed, $index out of Bounds');
}
}
public function addChild($value) {
$this->children [] = $value;
}
}
class GenericTreeTest {
public function StartTest() {
echo "Starting Test. <br>";
$preOp = function () {
echo "( ";
};
$inOp = function ($arg) {
echo " $arg ";
};
$postOp = function (){
echo " )";
};
$tree = new GenericTree();
$tree->insert(array (), "1");
$tree->insert(array (), "2");
$tree->insert(array (), "3");
$tree->insert(array (), "4");
$tree->insert(array (3), "4,1");
$tree->insert(array (3), "4,2");
$tree->insert(array (2), "3,1");
$tree->insert(array (2,0), "3,1,1");
echo $tree->inOrder($preOp, $inOp, $postOp);
//prints ( 1 ( ) 2 ( ) 3 ( 3,1 ( 3,1,1 ( ) ) ) 4 ( 4,1 ( ) 4,2 ( ) ) )
echo "<br> Ending Test.";
}
}
$gt = new GenericTreeTest();
$gt->startTest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment