AVL Tree Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓AVL Tree runs in O(log n) time and O(n) space, in C# as in every other language.
- ✓No AVL tree. SortedDictionary and SortedSet are red-black trees, and SortedList is a pair of sorted arrays.
- ✓Use SortedDictionary for ordered data and write an AVL only when you need the tighter height bound or the node handles.
- ✓The C# trap: The comparer traps that hit SortedSet apply to any tree you write on top of IComparer: a comparer returning zero for values you consider distinct silently collapses them into one node.
- ✓Reified generics mean an AvlTree<int> stores raw integers with no boxing whatsoever, which is a real advantage over the equivalent Java code where every key becomes an Integer object.
What AVL Tree actually is
AVL Tree in C#: what you actually reach for
C# implementation
using System.Collections.Generic;
public sealed class AvlTree<TKey>
{
private sealed class Node
{
public TKey Key;
public Node? Left, Right;
public int Height = 1;
public Node(TKey key) => Key = key;
}
private Node? _root;
private readonly IComparer<TKey> _cmp;
// Framework convention: accept a comparer, default to Comparer<T>.Default.
public AvlTree(IComparer<TKey>? comparer = null)
=> _cmp = comparer ?? Comparer<TKey>.Default;
private static int H(Node? n) => n?.Height ?? 0;
private static void Update(Node n) => n.Height = 1 + System.Math.Max(H(n.Left), H(n.Right));
private static int Balance(Node? n) => n is null ? 0 : H(n.Left) - H(n.Right);
private static Node RotateRight(Node y)
{
var x = y.Left!;
y.Left = x.Right;
x.Right = y;
Update(y); // lower node first
Update(x);
return x;
}
private static Node RotateLeft(Node x)
{
var y = x.Right!;
x.Right = y.Left;
y.Left = x;
Update(x);
Update(y);
return y;
}
public void Insert(TKey key) => _root = Insert(_root, key);
private Node Insert(Node? node, TKey key)
{
if (node is null) return new Node(key);
int c = _cmp.Compare(key, node.Key);
if (c < 0) node.Left = Insert(node.Left, key);
else if (c > 0) node.Right = Insert(node.Right, key);
else return node; // comparer said "equal": one node, as designed
Update(node);
int b = Balance(node);
if (b > 1 && _cmp.Compare(key, node.Left!.Key) < 0) return RotateRight(node);
if (b < -1 && _cmp.Compare(key, node.Right!.Key) > 0) return RotateLeft(node);
if (b > 1) { node.Left = RotateLeft(node.Left!); return RotateRight(node); }
if (b < -1) { node.Right = RotateRight(node.Right!); return RotateLeft(node); }
return node;
}
public bool Contains(TKey key)
{
var node = _root;
while (node is not null)
{
int c = _cmp.Compare(key, node.Key);
if (c == 0) return true;
node = c < 0 ? node.Left : node.Right;
}
return false;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for AVL Tree?
No AVL tree. SortedDictionary and SortedSet are red-black trees, and SortedList is a pair of sorted arrays. The framework has no strictly height-balanced binary tree.
What is the most common C# mistake when implementing AVL Tree?
The comparer traps that hit SortedSet apply to any tree you write on top of IComparer: a comparer returning zero for values you consider distinct silently collapses them into one node. In the framework collections this manifests as Add returning false and the item disappearing, which is easy to miss because Add is usually called for its effect rather than its result. When implementing IComparer<K> yourself, make sure it is a total order over the whole key space, including nulls, because Comparer<K>.Default sorts null before everything and a hand-written comparer that dereferences its arguments will throw instead.
How does AVL Tree actually perform in C#?
Reified generics mean an AvlTree<int> stores raw integers with no boxing whatsoever, which is a real advantage over the equivalent Java code where every key becomes an Integer object. The nodes themselves are class instances with a sixteen-byte header, so a struct-of-arrays layout indexed by integer is the faster design when the tree is large and the key is a value type. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.