AVL Tree Implementation in Python
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 your Data Structures question into a ready to paste AI prompt, free →
Key Takeaways
- ✓AVL Tree runs in O(log n) time and O(n) space, in Python as in every other language.
- ✓None, and no ordered mapping at all. The de-facto community answer is the third-party sortedcontainers package, which is worth knowing because it does not use a tree: it keeps a list of short lists and relies on C-speed list operations to beat a pure-Python tree comfortably.
- ✓Write a module-level height helper that returns zero for None rather than reading a node attribute, because node.height on None raises AttributeError and the null case appears in every rotation.
- ✓The Python trap: Python 3 raises TypeError when it compares values of unorderable types, so a tree that accepts whatever the caller inserts fails at the first comparison between, say, an int and a str, deep inside a rotation rather than at the API boundary.
- ✓A pure-Python node tree is roughly two orders of magnitude slower than the C-implemented dict, and sortedcontainers beats it too, because its inner loops are list slicing in C rather than interpreted pointer updates.
What AVL Tree actually is
AVL Tree in Python: what you actually reach for
Python implementation
class Node:
__slots__ = ("key", "left", "right", "height")
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
def _h(node) -> int:
# A helper, not node.height: attribute access on None is AttributeError
# and the None case appears in every rotation.
return node.height if node else 0
def _balance(node) -> int:
return _h(node.left) - _h(node.right)
def _update(node) -> None:
node.height = 1 + max(_h(node.left), _h(node.right))
def _rotate_right(y: Node) -> Node:
x = y.left
y.left = x.right
x.right = y
_update(y) # the LOWER node first: y is now x's child
_update(x)
return x
def _rotate_left(x: Node) -> Node:
y = x.right
x.right = y.left
y.left = x
_update(x)
_update(y)
return y
def insert(node, key):
if node is None:
return Node(key)
# TypeError here if key types are unorderable: Python 3 refuses to
# compare int with str, unlike Python 2 which ordered by type name.
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
else:
return node
_update(node)
b = _balance(node)
if b > 1 and key < node.left.key: # left-left
return _rotate_right(node)
if b < -1 and key > node.right.key: # right-right
return _rotate_left(node)
if b > 1: # left-right
node.left = _rotate_left(node.left)
return _rotate_right(node)
if b < -1: # right-left
node.right = _rotate_right(node.right)
return _rotate_left(node)
return nodeThink 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 Python-specific trap
Performance in Python, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for AVL Tree?
None, and no ordered mapping at all. The de-facto community answer is the third-party sortedcontainers package, which is worth knowing because it does not use a tree: it keeps a list of short lists and relies on C-speed list operations to beat a pure-Python tree comfortably.
What is the most common Python mistake when implementing AVL Tree?
Python 3 raises TypeError when it compares values of unorderable types, so a tree that accepts whatever the caller inserts fails at the first comparison between, say, an int and a str, deep inside a rotation rather than at the API boundary. Python 2 silently ordered by type name instead, which is why ported code hits this. The related recursion point is worth stating precisely: the default recursion limit of one thousand is never a problem for a balanced AVL tree, whose depth is about 1.44 times the base-two logarithm of n, but it is exactly what a naive unbalanced BST hits after a thousand sorted inserts, which is the input AVL exists to survive.
How does AVL Tree actually perform in Python?
A pure-Python node tree is roughly two orders of magnitude slower than the C-implemented dict, and sortedcontainers beats it too, because its inner loops are list slicing in C rather than interpreted pointer updates. 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 Devin 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.