LevelOrderVisitor::traverseLevelOrder()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 6
c 1
b 0
f 1
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 10
cc 3
nc 3
nop 2
crap 3
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