Created
September 12, 2011 19:22
-
-
Save asterite/1212115 to your computer and use it in GitHub Desktop.
My linked list
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
<? | |
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