forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAVLTreeNode.cs
72 lines (65 loc) · 2.03 KB
/
AVLTreeNode.cs
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
using System;
namespace DataStructures.AVLTree
{
/// <summary>
/// Generic class to represent nodes in an <see cref="AvlTree{TKey}"/> instance.
/// </summary>
/// <typeparam name="TKey">The type of key for the node.</typeparam>
public class AvlTreeNode<TKey>
{
/// <summary>
/// Gets or sets key value of node.
/// </summary>
public TKey Key { get; set; }
/// <summary>
/// Gets the height of the node.
/// </summary>
public int Height { get; private set; }
/// <summary>
/// Gets the balance factor of the node.
/// </summary>
public int BalanceFactor { get; private set; }
/// <summary>
/// Gets or sets the left child of the node.
/// </summary>
public AvlTreeNode<TKey>? Left { get; set; }
/// <summary>
/// Gets or sets the right child of the node.
/// </summary>
public AvlTreeNode<TKey>? Right { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="AvlTreeNode{TKey}"/> class.
/// </summary>
/// <param name="key">Key value for node.</param>
public AvlTreeNode(TKey key)
{
Key = key;
}
/// <summary>
/// Update the node's height and balance factor.
/// </summary>
public void UpdateBalanceFactor()
{
if(Left is null && Right is null)
{
Height = 0;
BalanceFactor = 0;
}
else if(Left is null)
{
Height = Right!.Height + 1;
BalanceFactor = Height;
}
else if(Right is null)
{
Height = Left!.Height + 1;
BalanceFactor = -Height;
}
else
{
Height = Math.Max(Left.Height, Right.Height) + 1;
BalanceFactor = Right.Height - Left.Height;
}
}
}
}