-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinaryTreeNode.php
More file actions
102 lines (93 loc) · 2.13 KB
/
BinaryTreeNode.php
File metadata and controls
102 lines (93 loc) · 2.13 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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace DesignPatterns\Structural\Adapter\BinaryTree;
/**
* A node of binary tree.
* Can be a root, can be a leaf, can be an intermediate node.
*
* @author Vlad Riabchenko <contact@vria.eu>
*/
class BinaryTreeNode
{
/**
* The value of this node.
*
* @var int
*/
private $value;
/**
* Optional left child.
* It's value is always lower than the value of this node.
*
* @var BinaryTreeNode
*/
private $left;
/**
* Optional right child.
* It's value is always higher or equal than the value of this node.
*
* @var BinaryTreeNode
*/
private $right;
/**
* @param int $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* Insert a value.
* This method always creates a new node somewhere down the tree.
*
* @param int $value
*/
public function insert($value)
{
if ($this->value <= $value) {
// Insert in right subtree.
if ($this->right) {
// If right child already exists then pass the value to it.
$this->right->insert($value);
} else {
// If not then create a new right child.
$this->right = new BinaryTreeNode($value);
}
} elseif ($this->value > $value) {
// Insert in left subtree.
if ($this->left) {
// If left child already exists then pass the value to it.
$this->left->insert($value);
} else {
// If not then create a new left child.
$this->left = new BinaryTreeNode($value);
}
}
}
/**
* Get value.
*
* @return int
*/
public function getValue()
{
return $this->value;
}
/**
* Get left child node.
*
* @return BinaryTreeNode
*/
public function getLeft()
{
return $this->left;
}
/**
* Get right child node.
*
* @return BinaryTreeNode
*/
public function getRight()
{
return $this->right;
}
}