Reputation: 12720
Is there a module for an AVL tree or a red–black tree or some other type of a balanced binary tree in the standard library of Python?
Upvotes: 111
Views: 68582
Reputation: 31
I wrote a Python version of the Java TreeMap/TreeSet, of which the underlying data structure is a balanced binary tree (Red-Black tree to be precise).
Source code and documentation can be accessed in this repo
You can install with pip install pytreemap
.
Tested for Python >=3.5
Upvotes: 1
Reputation: 6356
Check out also the Sorted Containers project.
Here's a PyCon talk about it: https://www.youtube.com/watch?v=7z2Ki44Vs4E
Upvotes: 11
Reputation: 22679
There is a new package called "bintrees" which supports ubalanced, AVL and RB trees. You can find it here.
Upvotes: 7
Reputation: 319881
there is nothing of this sort in stdlib, as far as I can see, but quick look at pypi brings up a few alternative:
Upvotes: 16
Reputation: 5124
There have been a few instances where I have found the heapq package (in the stadndard library) to be useful, especially if at any given time you want O(1) access time to the smallest element in your collection.
For me, I was keeping track of a collection of timers and was usually just interested in checking if the smallest time (the one to be executed first) was ready to go as of yet.
Upvotes: 13
Reputation: 76753
No, there is not a balanced binary tree in the stdlib. However, from your comments, it sounds like you may have some other options:
O(log n)
searches. If searching is all you need and your data are already sorted, the bisect
module provides a binary search algorithm for lists.If neither solution works well for you, you'll have to go to a third party module or implement your own.
Upvotes: 58
Reputation: 70208
No, but there's AVL Tree Objects for Python (very old!) and a (closed) project on SourceForge - avl-trees for Python.
Upvotes: 4