Is there a module for balanced binary tree in Python's standard library?

PythonTreeStandard Library

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

No, there is not a balanced binary tree in the stdlib. However, from your comments, it sounds like you may have some other options:

  • You say that you want a BST instead of a list for 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.
  • Mike DeSimone recommended sets and dicts and you explained why lists are too algorithmically slow. Sets and dicts are implemented as hash tables, which have O(1) lookup. The solution to most problems in Python really is "use a dict".

If neither solution works well for you, you'll have to go to a third party module or implement your own.

Solution 2 - Python

Solution 3 - Python

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.

Solution 4 - Python

Check out also the Sorted Containers project.

Here's a PyCon talk about it: https://www.youtube.com/watch?v=7z2Ki44Vs4E

Solution 5 - Python

There is a new package called "bintrees" which supports ubalanced, AVL and RB trees. You can find it here.

Solution 6 - Python

No, but there's AVL Tree Objects for Python (very old!) and a (closed) project on SourceForge - avl-trees for Python.

Solution 7 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaeterView Question on Stackoverflow
Solution 1 - PythonMike GrahamView Answer on Stackoverflow
Solution 2 - PythonSilentGhostView Answer on Stackoverflow
Solution 3 - PythonPaul OsborneView Answer on Stackoverflow
Solution 4 - PythonpostrationalView Answer on Stackoverflow
Solution 5 - PythonZaur NasibovView Answer on Stackoverflow
Solution 6 - PythonAndiDogView Answer on Stackoverflow
Solution 7 - PythonGavinPHRView Answer on Stackoverflow