Skip to content

Instantly share code, notes, and snippets.

@asterite
Created September 12, 2011 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asterite/1212115 to your computer and use it in GitHub Desktop.
Save asterite/1212115 to your computer and use it in GitHub Desktop.
My linked list
<?
class Tree {
function add($value) {
if (!isset($this->value)) {
$this->value = $value;
return;
}
if ($value < $this->value) {
if (!$this->left) $this->left = new Tree();
$this->left->add($value);
} else if ($value > $this->value) {
if (!$this->right) $this->right = new Tree();
$this->right->add($value);
}
}
function toList() {
$array = array();
$this->toArray($array);
$arrayLength = count($array);
for($i = 0; $i < $arrayLength; $i++) {
if ($i > 0) {
$array[$i]->left = $array[$i - 1];
}
if ($i < $arrayLength - 1) {
$array[$i]->right = $array[$i + 1];
}
}
return $array;
}
private function toArray(&$array) {
if ($this->left) {
$this->left->toArray($array);
}
$array[] = $this;
if ($this->right) {
$this->right->toArray($array);
}
}
}
$tree = new Tree();
$tree->add(10);
$tree->add(5);
$tree->add(15);
$tree->add(14);
$tree->add(12);
$tree->add(13);
$tree->add(16);
$tree->add(17);
$tree->add(2);
$tree->add(8);
$tree->add(7);
$tree->add(9);
print_r($tree);
$list = $tree->toList();
foreach($list as $node) {
echo $node->value;
echo " (left: ";
if ($node->left) {
echo $node->left->value;
} else {
echo "none";
}
echo ", right: ";
if ($node->right) {
echo $node->right->value;
} else {
echo "none";
}
echo ")\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment