AVL Tree Implementation in Java
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 Java as in every other language.
- ✓No AVL tree. TreeMap and TreeSet are red-black trees, which maintain a looser balance invariant: a red-black tree may be up to twice as deep as a perfectly balanced tree, where an AVL tree is capped at about 1.44 times the base-two logarithm of n.
- ✓Use TreeMap unless you have measured that lookups dominate writes heavily enough to justify the tighter AVL bound, which in practice is rare.
- ✓The Java trap: The recurring Java-specific trap in any ordered structure is the contract between compareTo and equals.
- ✓Every node is an object with a header plus references to key, value, left, right and parent, plus a colour, so roughly forty-eight bytes per mapping, all scattered.
What AVL Tree actually is
AVL Tree in Java: what you actually reach for
Java implementation
public final class AvlTree<K extends Comparable<K>> {
private static final class Node<K> {
final K key;
Node<K> left, right;
int height = 1;
Node(K key) { this.key = key; }
}
private Node<K> root;
private static int height(Node<?> n) { return n == null ? 0 : n.height; }
private static void update(Node<?> n) {
n.height = 1 + Math.max(height(n.left), height(n.right));
}
private static <K> int balance(Node<K> n) {
return n == null ? 0 : height(n.left) - height(n.right);
}
private static <K> Node<K> rotateRight(Node<K> y) {
Node<K> x = y.left;
y.left = x.right;
x.right = y;
update(y); // lower node first
update(x);
return x;
}
private static <K> Node<K> rotateLeft(Node<K> x) {
Node<K> y = x.right;
x.right = y.left;
y.left = x;
update(x);
update(y);
return y;
}
public void insert(K key) { root = insert(root, key); }
private Node<K> insert(Node<K> node, K key) {
if (node == null) return new Node<>(key);
int c = key.compareTo(node.key);
if (c < 0) node.left = insert(node.left, key);
else if (c > 0) node.right = insert(node.right, key);
else return node;
update(node);
int b = balance(node);
if (b > 1 && key.compareTo(node.left.key) < 0) return rotateRight(node);
if (b < -1 && key.compareTo(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;
}
}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 Java-specific trap
Performance in Java, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for AVL Tree?
No AVL tree. TreeMap and TreeSet are red-black trees, which maintain a looser balance invariant: a red-black tree may be up to twice as deep as a perfectly balanced tree, where an AVL tree is capped at about 1.44 times the base-two logarithm of n.
What is the most common Java mistake when implementing AVL Tree?
The recurring Java-specific trap in any ordered structure is the contract between compareTo and equals. TreeMap and TreeSet determine identity entirely by the comparison result, so two objects that are not equal but compare as zero become one entry, and the collection silently loses data while obeying its own documented behaviour. Using String.CASE_INSENSITIVE_ORDER as a TreeMap comparator is the standard demonstration: putting Key and then KEY leaves a map of size one. Both also reject null keys with a NullPointerException.
How does AVL Tree actually perform in Java?
Every node is an object with a header plus references to key, value, left, right and parent, plus a colour, so roughly forty-eight bytes per mapping, all scattered. Autoboxing applies to primitive keys because generics are erased, and there is no primitive-specialised ordered map in the JDK. 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 trialBefore paying for GitHub Copilot, check its student and free-tier options 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.