-
-
Notifications
You must be signed in to change notification settings - Fork 585
Expand file tree
/
Copy pathCompareBinaryTree.php
More file actions
35 lines (29 loc) · 1.11 KB
/
Copy pathCompareBinaryTree.php
File metadata and controls
35 lines (29 loc) · 1.11 KB
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
<?php
declare(strict_types=1);
namespace DataStructures\CompareBinaryTree;
/**
* Recurrent comparison of binary trees based on comparison of left and right branches
* (https://en.wikipedia.org/wiki/Binary_tree).
*
* @author Michał Żarnecki https://github.com/rzarno
*/
class CompareBinaryTree
{
/**
* compare two binary trees
*/
public function areTreesEqual(?BinaryTreeNode $a, ?BinaryTreeNode $b): bool
{
if (!$a instanceof \DataStructures\CompareBinaryTree\BinaryTreeNode && $b instanceof \DataStructures\CompareBinaryTree\BinaryTreeNode || $a instanceof \DataStructures\CompareBinaryTree\BinaryTreeNode && !$b instanceof \DataStructures\CompareBinaryTree\BinaryTreeNode) {
return false;
}
if (!$a instanceof \DataStructures\CompareBinaryTree\BinaryTreeNode && !$b instanceof \DataStructures\CompareBinaryTree\BinaryTreeNode) {
return true;
}
if ($a->value !== $b->value) {
return false;
}
return $this->areTreesEqual($a->left, $b->left)
&& $this->areTreesEqual($a->right, $b->right);
}
}