Created
November 26, 2013 09:03
-
-
Save tomphp/7655395 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 extends RecursiveArrayIterator | |
{ | |
public function __construct($nodes) | |
{ | |
if (!is_array($nodes)) { | |
$nodes = [$nodes]; | |
} | |
parent::__construct($nodes); | |
} | |
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