Skip to content

Commit 7927ee0

Browse files
committed
BinarySearchTree with objects
1 parent 5f361a2 commit 7927ee0

File tree

2 files changed

+54
-4
lines changed

2 files changed

+54
-4
lines changed

src/Datastructure/Graph/Tree/BinaryTree/BinarySearchNode.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class BinarySearchNode implements IBinaryNode {
4242
*
4343
* @param int $value
4444
*/
45-
public function __construct(int $value) {
45+
public function __construct($value) {
4646
$this->value = $value;
4747
}
4848

@@ -97,14 +97,14 @@ public function compareTo($object): int {
9797
/**
9898
* @return int
9999
*/
100-
public function getValue(): int {
100+
public function getValue() {
101101
return $this->value;
102102
}
103103

104104
/**
105105
* @param int $value
106106
*/
107-
public function setValue(int $value): void {
107+
public function setValue($value): void {
108108
$this->value = $value;
109109
}
110110
}

tests/Graph/trees/BinarySearchTreeTest.php

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
use doganoo\PHPAlgorithms\Algorithm\Traversal\InOrder;
2727
use doganoo\PHPAlgorithms\Algorithm\Traversal\PostOrder;
2828
use doganoo\PHPAlgorithms\Algorithm\Traversal\PreOrder;
29+
use doganoo\PHPAlgorithms\Common\Interfaces\Comparable;
2930
use doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinarySearchTree;
3031

3132
/**
@@ -85,4 +86,53 @@ public function testPostOrder() {
8586
$traversal->traverse();
8687
$this->assertTrue($array === [1, 2, 6, 5]);
8788
}
88-
}
89+
90+
public function testWithObjects() {
91+
$tree = new BinarySearchTree();
92+
$upper = 10;
93+
for ($i = 0; $i < $upper; $i++) {
94+
$x = new TestNode($i);
95+
$tree->insertValue($x);
96+
}
97+
$this->assertTrue($tree->height() === $upper);
98+
$node = $tree->search(new TestNode(4));
99+
$this->assertTrue($node !== null);
100+
$node = $tree->search(new TestNode($upper + 5));
101+
$this->assertTrue($node === null);
102+
103+
}
104+
}
105+
106+
class TestNode implements Comparable {
107+
private $id = 0;
108+
109+
public function __construct($id) {
110+
$this->id = $id;
111+
}
112+
113+
/**
114+
* @param $object
115+
* @return int
116+
*/
117+
public function compareTo($object): int {
118+
if (!$object instanceof $this) {
119+
return -1;
120+
}
121+
if ($this->getId() < $object->getId()) {
122+
return -1;
123+
}
124+
if ($this->getId() == $object->getId()) {
125+
return 0;
126+
}
127+
if ($this->getId() > $object->getId()) {
128+
return 1;
129+
}
130+
return -1;
131+
}
132+
133+
public function getId(): int {
134+
return $this->id;
135+
}
136+
}
137+
138+
;

0 commit comments

Comments
 (0)