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 InvalidArgumentException; |
15
|
|
|
use Seboettg\Collection\ArrayList; |
16
|
|
|
use Seboettg\Collection\ArrayList\ArrayListInterface; |
17
|
|
|
use Seboettg\Forest\BinaryTree\BinaryNodeInterface; |
18
|
|
|
use Seboettg\Forest\General\TreeNodeInterface; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Class InOrderVisitor |
22
|
|
|
* Implements the tree traversal strategy In-order. |
23
|
|
|
* In this traversal strategy, the left subtree is visited first, then the root and later the right sub-tree. |
24
|
|
|
* If a binary tree is traversed in-order, the output will produce sorted key values in an ascending order. |
25
|
|
|
* |
26
|
|
|
* @package Seboettg\Forest\Visitor |
27
|
|
|
*/ |
28
|
|
|
class InOrderVisitor implements VisitorInterface |
29
|
|
|
{ |
30
|
|
|
|
31
|
17 |
|
public function visit(TreeNodeInterface $node): ArrayListInterface |
32
|
|
|
{ |
33
|
17 |
|
if (!$node instanceof BinaryNodeInterface) { |
34
|
1 |
|
throw new InvalidArgumentException(BinaryNodeInterface::class . " expected, got " . get_class($node) . "."); |
35
|
|
|
} |
36
|
16 |
|
$resultList = new ArrayList(); |
37
|
16 |
|
if ($node !== null) { |
38
|
16 |
|
$left = $node->getLeft(); |
39
|
16 |
|
$right = $node->getRight(); |
40
|
16 |
|
if ($left !== null) { |
41
|
16 |
|
$resultList->merge($left->accept($this)); |
42
|
|
|
} |
43
|
16 |
|
$resultList->append($node->getItem()); |
44
|
16 |
|
if ($right !== null) { |
45
|
16 |
|
$resultList->merge($right->accept($this)); |
46
|
|
|
} |
47
|
|
|
} |
48
|
16 |
|
return $resultList; |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|