-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTree.php
60 lines (52 loc) · 1.35 KB
/
BinarySearchTree.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
<?php
class BinarySearchTree
{
private $root;
public function __construct()
{
$this->root = null;
}
public function insert($data)
{
$node = new Node($data);
if ($this->root === null) {
$this->root = $node;
} else {
$this->insertNode($this->root, $node);
}
}
private function insertNode(&$node, &$newNode)
{
if ($newNode->data < $node->data) {
if ($node->left === null) {
$node->left = $newNode;
} else {
$this->insertNode($node->left, $newNode);
}
} else if ($newNode->data > $node->data) {
if ($node->right === null) {
$node->right = $newNode;
} else {
$this->insertNode($node->right, $newNode);
}
}
}
public function search($data)
{
return $this->searchNode($this->root, $data);
}
private function searchNode($node, $data)
{
if ($node === null || $node->data === null) {
return null;
}
if ($data === $node->data) {
return $node->data;
}
if ($data < $node->data) {
return $this->searchNode($node->left, $data);
} else {
return $this->searchNode($node->right, $data);
}
}
}