Python's standard library - is there a module for balanced binary tree?

不羁的心 提交于 2019-11-26 18:47:53

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.

SilentGhost

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.

Zaur Nasibov

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

Check out also the Sorted Containers project.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!