Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 281
aeter Avatar asked Feb 19 '10 17:02

aeter


People also ask

How do you implement a balanced binary tree in Python?

Approach to Solve this ProblemTake input of nodes of a Binary Tree. Define a function to find the height of the tree. A Boolean function to check recursively if the height difference of left subtree and right subtree is not more than '1', then return True. Return the Result.

Does Python have a built in binary search tree?

The binary search tree is a special type of tree data structure whose inorder gives a sorted list of nodes or vertices. In Python, we can directly create a BST object using binarytree module. bst() generates a random binary search tree and return its root node. is_perfect: If set True a perfect binary is created.

What is TreeNode in Python?

Python TreeNode class A TreeNode is a data structure that represents one entry of a tree, which is composed of multiple of such nodes. The topmost node of a tree is called the “root”, and each node (with the exception of the root node) is associated with one parent node.


1 Answers

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.

like image 74
Mike Graham Avatar answered Oct 23 '22 08:10

Mike Graham