|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
/* |
|
4
|
|
|
* Copyright (C) 2019 Sebastian Böttger <[email protected]> |
|
5
|
|
|
* You may use, distribute and modify this code under the |
|
6
|
|
|
* terms of the MIT license. |
|
7
|
|
|
* |
|
8
|
|
|
* You should have received a copy of the MIT license with |
|
9
|
|
|
* this file. If not, please visit: https://opensource.org/licenses/mit-license.php |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Seboettg\Forest\Visitor; |
|
13
|
|
|
|
|
14
|
|
|
use Seboettg\Collection\ArrayList; |
|
15
|
|
|
use Seboettg\Collection\ArrayList\ArrayListInterface; |
|
16
|
|
|
use Seboettg\Collection\Queue; |
|
17
|
|
|
use Seboettg\Forest\General\TreeNodeInterface; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Class LevelOrderVisitor |
|
21
|
|
|
* Implements the tree traversal strategy Level-order. |
|
22
|
|
|
* In this traversal strategy, the root node is visited first, than all nodes of the next level and so on. |
|
23
|
|
|
* |
|
24
|
|
|
* @package Seboettg\Forest\Visitor |
|
25
|
|
|
*/ |
|
26
|
|
|
class LevelOrderVisitor implements VisitorInterface |
|
27
|
|
|
{ |
|
28
|
|
|
|
|
29
|
3 |
|
public function visit(TreeNodeInterface $node): ArrayListInterface |
|
30
|
|
|
{ |
|
31
|
3 |
|
$result = new ArrayList(); |
|
32
|
3 |
|
$queue = new Queue(); |
|
33
|
3 |
|
$queue->enqueue($node); |
|
34
|
3 |
|
return $this->traverseLevelOrder($result, $queue); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @param ArrayListInterface $target |
|
39
|
|
|
* @param Queue $queue |
|
40
|
|
|
* @return ArrayListInterface |
|
41
|
|
|
*/ |
|
42
|
3 |
|
private function traverseLevelOrder(ArrayListInterface $target, Queue $queue): ArrayListInterface |
|
43
|
|
|
{ |
|
44
|
3 |
|
while ($queue->count() > 0) { |
|
45
|
|
|
/** @var TreeNodeInterface $node */ |
|
46
|
3 |
|
$node = $queue->dequeue(); |
|
47
|
|
|
//enqueue all children to the queue for traversing the next level |
|
48
|
3 |
|
foreach ($node->getChildren() as $child) { |
|
49
|
3 |
|
$queue->enqueue($child); |
|
50
|
|
|
} |
|
51
|
3 |
|
$target->append($node->getItem()); |
|
52
|
|
|
} |
|
53
|
3 |
|
return $target; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|