Using binarytree module in Python for Binary Tree
Here, we will learn about the binarytree module in Python.
A binary tree is a method of placing and locating files (called records or keys) in a database, especially when all the data is known to be in random access memory (RAM). A binary tree is a data structure in which every node has almost two children ie left node and a right node.
Python provides an inbuilt module “binarytree” for the implementation of the data structure. In this tutorial, we will learn various operations that can be performed using this module.
binarytree Module in Python
To install this module use the below command in terminal:
pip install binarytree
Here we will cover basic functions present in the binarytree module.
- Creation of tree using Node() and Build().
- Tree Traversing (Inoder, Preorder, and Postorder)
Creation of tree using Node()
For creating a node we use the pre-defined function Node.
from binarytree import Node root = Node(1) // create a root node root.left = Node(2) //create left child root.right = Node(3) //create right child print("The binary tree created is: ", root)
Here, I have created a binary tree with a root node as 1, left child as 2 and right child as 3.
1 / \ 2 3
Creation of tree using build()
The build() method creates a binary tree using a list of values that need to be provided by the user.
from binarytree import build values=[1,2,3,4,5,6,7] tree = build(values) print(tree)
1 / \ 2 3 / \ / \ 4 5 6 7
Various other Operations that can be performed on trees are as follows:
- Check size of node: use root.size
- Check the height of node: use root.height
- Print list of nodes: use list(root)
- Check if balanced: root.is_balanced
- Leaf count: root.leaf_count
- Print levels of a tree: root.levels
- Print leaves: root.leaves
For other operations on the binary tree you can refer:
Traverse Tree in different orders
There are three ways to traverse a tree :
- Inorder Traversal
- Postorder Traversal
- Preorder Traversal
>>Inorder Traversal: Left node, Root node, Right node
>>For Postorder Traversal: Left node, Right node, Root node
>>For Preorder Traversal: Root node, Left node, Right node