forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNode.cs
87 lines (71 loc) · 2.41 KB
/
Node.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
namespace DataStructures.ScapegoatTree;
/// <summary>
/// Scapegoat tree node class.
/// </summary>
/// <typeparam name="TKey">Scapegoat tree node key type.</typeparam>
public class Node<TKey> where TKey : IComparable
{
private Node<TKey>? right;
private Node<TKey>? left;
public TKey Key { get; }
public Node<TKey>? Right
{
get => right;
set
{
if (value != null && !value.IsGreaterThanOrSameAs(Key))
{
throw new ArgumentException("The value's key is smaller than or equal to node's right child's key.", nameof(value));
}
right = value;
}
}
public Node<TKey>? Left
{
get => left;
set
{
if (value != null && value.IsGreaterThanOrSameAs(Key))
{
throw new ArgumentException("The value's key is greater than or equal to node's left child's key.", nameof(value));
}
left = value;
}
}
public Node(TKey key) => Key = key;
public Node(TKey key, Node<TKey>? right, Node<TKey>? left)
: this(key)
{
Right = right;
Left = left;
}
/// <summary>
/// Returns number of elements in the tree.
/// </summary>
/// <returns>Number of elements in the tree.</returns>
public int GetSize() => (Left?.GetSize() ?? 0) + 1 + (Right?.GetSize() ?? 0);
/// <summary>
/// Gets alpha height of the current node.
/// </summary>
/// <param name="alpha">Alpha value.</param>
/// <returns>Alpha height value.</returns>
public double GetAlphaHeight(double alpha) => Math.Floor(Math.Log(GetSize(), 1.0 / alpha));
public Node<TKey> GetSmallestKeyNode() => Left?.GetSmallestKeyNode() ?? this;
public Node<TKey> GetLargestKeyNode() => Right?.GetLargestKeyNode() ?? this;
/// <summary>
/// Checks if the current node is alpha weight balanced.
/// </summary>
/// <param name="a">Alpha value.</param>
/// <returns>True - if node is alpha weight balanced. If not - false.</returns>
public bool IsAlphaWeightBalanced(double a)
{
var isLeftBalanced = (Left?.GetSize() ?? 0) <= a * GetSize();
var isRightBalanced = (Right?.GetSize() ?? 0) <= a * GetSize();
return isLeftBalanced && isRightBalanced;
}
private bool IsGreaterThanOrSameAs(TKey key)
{
return Key.CompareTo(key) >= 0;
}
}