forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVLTreeNode.php
49 lines (43 loc) · 1.26 KB
/
AVLTreeNode.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
<?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;
class AVLTreeNode
{
/**
* @var int|string
*/
public $key;
/**
* @var mixed
*/
public $value;
public ?AVLTreeNode $left;
public ?AVLTreeNode $right;
public int $height;
public function __construct($key, $value, ?AVLTreeNode $left = null, ?AVLTreeNode $right = null)
{
$this->key = $key;
$this->value = $value;
$this->left = $left;
$this->right = $right;
$this->height = 1; // New node is initially at height 1
}
public function updateHeight(): void
{
$leftHeight = $this->left ? $this->left->height : 0;
$rightHeight = $this->right ? $this->right->height : 0;
$this->height = max($leftHeight, $rightHeight) + 1;
}
public function balanceFactor(): int
{
$leftHeight = $this->left ? $this->left->height : 0;
$rightHeight = $this->right ? $this->right->height : 0;
return $leftHeight - $rightHeight;
}
}