Skip to content

Instantly share code, notes, and snippets.

@tomphp
Created November 26, 2013 08:54
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 tomphp/7655299 to your computer and use it in GitHub Desktop.
Save tomphp/7655299 to your computer and use it in GitHub Desktop.
<?php
class TreeNode
{
private $place;
private $children = [];
public function __construct($place)
{
$this->place = $place;
}
public function add(TreeNode $node)
{
$this->children[] = $node;
}
public function getPlace()
{
return $this->place;
}
public function getChildren()
{
return $this->children;
}
}
class TreeIterator implements RecursiveIterator
{
private $nodes = array();
public function __construct($nodes)
{
if (is_array($nodes)) {
$this->nodes = $nodes;
} elseif ($nodes instanceof TreeNode) {
$this->nodes = [$nodes];
} else {
throw \InvalidArgumentException();
}
}
public function current()
{
return current($this->nodes);
}
public function key()
{
return key($this->nodes);
}
public function next()
{
next($this->nodes);
}
public function rewind()
{
reset($this->nodes);
}
public function valid()
{
return current($this->nodes) !== false;
}
public function getChildren()
{
return new TreeIterator($this->current()->getChildren());
}
public function hasChildren()
{
return 0 < count($this->current()->getChildren());
}
}
$one = new TreeNode(1);
$two = new TreeNode(2);
$three = new TreeNode(3);
$one->add($two);
$one->add($three);
$two->add(new TreeNode(4));
$two->add(new TreeNode(5));
$two->add(new TreeNode(6));
$it = new TreeIterator($one);
$rii = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
foreach ($rii as $node) {
echo "PLACE = " . $node->getPlace() . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment