Created
November 26, 2013 08:54
-
-
Save tomphp/7655299 to your computer and use it in GitHub Desktop.
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
<?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