views:

285

answers:

5

Is there a module for AVL or Red-Black or some other type of a balanced binary tree in the standard library of Python? I have tried to find one, but unsuccessfully (I'm relatively new to Python).

+1  A: 

there is nothing of this sort in stdlib, as far as I can see, but quick look at pypi brings up a few alternative:

SilentGhost
A: 

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

AndiDog
+4  A: 

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.

Mike Graham
Thank you very much! Using a set solved my problem. I had no idea they have O(1) lookups in Python (I have always thought that the whole set should be traversed before finding the right value - but as I said, I'm new to Python). Thank you also for your explanation for the usual data structures in Python.
aeter
A: 

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.

Paul Osborne
A: 

how should i implement the tree like this 50 30 80 15 45 65 95
10 20 35 48 55 70 90 100

avinash