Binarytree Module in Python
Last Updated :
10 Jan, 2023
A binary tree is a data structure in which every node or vertex has at most two children. In Python, a binary tree can be represented in different ways with different data structures(dictionary, list) and class representations for a node. However, binarytree library helps to directly implement a binary tree. It also supports heap and binary search tree(BST). This module does not come pre-installed with Python’s standard utility module. To install it type the below command in the terminal.
pip install binarytree
Creating Node
The node class represents the structure of a particular node in the binary tree. The attributes of this class are values, left, right.
Syntax: binarytree.Node(value, left=None, right=None)
Parameters:
value: Contains the data for a node. This value must be number.
left: Contains the details of left node child.
right: Contains details of the right node child.
Note: If left or right child node is not an instance of binarytree.Node class then binarytree.exceptions.NodeTypeError is raised and if the node value is not a number then binarytree.exceptions.NodeValueError is raised.
Example:
Python3
from binarytree import Node
root = Node( 3 )
root.left = Node( 6 )
root.right = Node( 8 )
print ( 'Binary tree :' , root)
print ( 'List of nodes :' , list (root))
print ( 'Inorder of nodes :' , root.inorder)
print ( 'Size of tree :' , root.size)
print ( 'Height of tree :' , root.height)
print ( 'Properties of tree : \n' , root.properties)
|
Output:
Binary tree :
3
/ \
6 8
List of nodes : [Node(3), Node(6), Node(8)]
Inorder of nodes : [Node(6), Node(3), Node(8)]
Size of tree : 3
Height of tree : 1
Properties of tree :
{‘height’: 1, ‘size’: 3, ‘is_max_heap’: False, ‘is_min_heap’: True, ‘is_perfect’: True, ‘is_strict’: True, ‘is_complete’: True, ‘leaf_count’: 2, ‘min_node_value’: 3, ‘max_node_value’: 8, ‘min_leaf_depth’: 1, ‘max_leaf_depth’: 1, ‘is_bst’: False, ‘is_balanced’: True, ‘is_symmetric’: False}
Build a binary tree from the List:
Instead of using the Node method repeatedly, we can use build() method to convert a list of values into a binary tree.
Here, a given list contains the nodes of tree such that the element at index i has its left child at index 2*i+1, the right child at index 2*i+2 and parent at (i – 1)//2. The elements at index j for j>len(list)//2 are leaf nodes. None indicates the absence of a node at that index. We can also get the list of nodes back after building a binary tree using values attribute.
Syntax: binarytree.build(values)
Parameters:
values: List representation of the binary tree.
Returns: root of the binary tree.
Example:
Python3
from binarytree import build
nodes = [ 3 , 6 , 8 , 2 , 11 , None , 13 ]
binary_tree = build(nodes)
print ( 'Binary tree from list :\n' ,
binary_tree)
print ( '\nList from binary tree :' ,
binary_tree.values)
|
Output:
Binary tree from list :
___3
/ \
6 8
/ \ \
2 11 13
List from binary tree : [3, 6, 8, 2, 11, None, 13]
Build a random binary tree:
tree() generates a random binary tree and returns its root node.
Syntax: binarytree.tree(height=3, is_perfect=False)
Parameters:
height: It is the height of the tree and its value can be between the range 0-9 (inclusive)
is_perfect: If set True a perfect binary is created.
Returns: Root node of the binary tree.
Example:
Python3
from binarytree import tree
root = tree()
print ( "Binary tree of any height :" )
print (root)
root2 = tree(height = 2 )
print ( "Binary tree of given height :" )
print (root2)
root3 = tree(height = 2 ,
is_perfect = True )
print ( "Perfect binary tree of given height :" )
print (root3)
|
Output:
Binary tree of any height :
14____
/ \
2 5__
/ / \
6 1 13
/ / / \
7 9 4 8
Binary tree of given height :
1__
/ \
5 2
/ \
4 3
Perfect binary tree of given height :
__3__
/ \
2 4
/ \ / \
6 0 1 5
Building a BST:
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.
Syntax: binarytree.bst(height=3, is_perfect=False)
Parameters:
height: It is the height of the tree and its value can be between the range 0-9 (inclusive)
is_perfect: If set True a perfect binary is created.
Returns: Root node of the BST.
Example:
Python3
from binarytree import bst
root = bst()
print ( 'BST of any height : \n' ,
root)
root2 = bst(height = 2 )
print ( 'BST of given height : \n' ,
root2)
root3 = bst(height = 2 ,
is_perfect = True )
print ( 'Perfect BST of given height : \n' ,
root3)
|
Output:
BST of any height :
____9______
/ \
__5__ ____12___
/ \ / \
2 8 10 _14
/ \ / \ /
1 4 7 11 13
BST of given height :
5
/ \
4 6
/
3
Perfect BST of given height :
__3__
/ \
1 5
/ \ / \
0 2 4 6
Importing heap:
Heap is a tree data structure that can be of two types –
Using the heap() method of binarytree library, we can generate a random maxheap and return its root node. To generate minheap, we need to set the is_max attribute as False.
Syntax: binarytree.heap(height=3, is_max=True, is_perfect=False)
Parameters:
height: It is the height of the tree and its value can be between the range 0-9 (inclusive)
is_max: If set True generates a max heap else min heap.
is_perfect: If set True a perfect binary is created.
Returns: Root node of the heap.
Python3
from binarytree import heap
root = heap()
print ( 'Max-heap of any height : \n' ,
root)
root2 = heap(height = 2 )
print ( 'Max-heap of given height : \n' ,
root2)
root3 = heap(height = 2 ,
is_max = False ,
is_perfect = True )
print ( 'Perfect min-heap of given height : \n' ,
root3)
|
Output:
Max-heap of any height :
_______14______
/ \
___12__ __13__
/ \ / \
10 8 3 9
/ \ / \ / \ /
1 5 4 6 0 2 7
Max-heap of given height :
__6__
/ \
4 5
/ \ / \
2 0 1 3
Perfect min-heap of given height :
__0__
/ \
1 3
/ \ / \
2 6 4 5
Similar Reads
Import module in Python
In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Pythonâs import st
3 min read
__future__ Module in Python
__future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module. It
4 min read
Python Fire Module
Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we w
3 min read
Built-in Modules in Python
Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include Python built-in modules and ext
9 min read
Inspect Module in Python
The inspect module in Python is useful for examining objects in your code. Since Python is an object-oriented language, this module helps inspect modules, functions and other objects to better understand their structure. It also allows for detailed analysis of function calls and tracebacks, making d
4 min read
Python Module Index
Python has a vast ecosystem of modules and packages. These modules enable developers to perform a wide range of tasks without taking the headache of creating a custom module for them to perform a particular task. Whether we have to perform data analysis, set up a web server, or automate tasks, there
4 min read
External Modules in Python
Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include built-in modules and external m
5 min read
Getopt module in Python
The getopt module is a parser for command-line options based on the convention established by the Unix getopt() function. It is in general used for parsing an argument sequence such as sys.argv. In other words, this module helps scripts to parse command-line arguments in sys.argv. It works similar t
2 min read
Binary Heap in Python
A Binary Heap is a complete Binary Tree that is used to store data efficiently to get the max or min element based on its structure. A Binary Heap is either a Min Heap or a Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in a Binary Heap. The same property
3 min read
Keyword Module in Python
Python provides an in-built module keyword that allows you to know about the reserved keywords of python. The keyword module allows you the functionality to know about the reserved words or keywords of Python and to check whether the value of a variable is a reserved word or not. In case you are una
2 min read