-
-
Notifications
You must be signed in to change notification settings - Fork 501
/
Copy pathTreeTraversal.php
88 lines (77 loc) · 2.48 KB
/
TreeTraversal.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/*
* Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) in Pull Request: #163
* https://github.com/TheAlgorithms/PHP/pull/163
*
* Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request addressing bugs/corrections to this file.
* Thank you!
*/
namespace DataStructures\AVLTree;
abstract class TreeTraversal
{
/**
* Perform an in-order traversal of the subtree.
* Recursively traverses the subtree rooted at the given node.
*/
public static function inOrder(?AVLTreeNode $node): array
{
$result = [];
if ($node !== null) {
$result = array_merge($result, self::inOrder($node->left));
$result[] = [$node->key => $node->value];
$result = array_merge($result, self::inOrder($node->right));
}
return $result;
}
/**
* Perform a pre-order traversal of the subtree.
* Recursively traverses the subtree rooted at the given node.
*/
public static function preOrder(?AVLTreeNode $node): array
{
$result = [];
if ($node !== null) {
$result[] = [$node->key => $node->value];
$result = array_merge($result, self::preOrder($node->left));
$result = array_merge($result, self::preOrder($node->right));
}
return $result;
}
/**
* Perform a post-order traversal of the subtree.
* Recursively traverses the subtree rooted at the given node.
*/
public static function postOrder(?AVLTreeNode $node): array
{
$result = [];
if ($node !== null) {
$result = array_merge($result, self::postOrder($node->left));
$result = array_merge($result, self::postOrder($node->right));
$result[] = [$node->key => $node->value];
}
return $result;
}
/**
* Perform a breadth-first traversal of the AVL Tree.
*/
public static function breadthFirst(?AVLTreeNode $root): array
{
$result = [];
if ($root === null) {
return $result;
}
$queue = [];
$queue[] = $root;
while (!empty($queue)) {
$currentNode = array_shift($queue);
$result[] = [$currentNode->key => $currentNode->value];
if ($currentNode->left !== null) {
$queue[] = $currentNode->left;
}
if ($currentNode->right !== null) {
$queue[] = $currentNode->right;
}
}
return $result;
}
}