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 databaseespecially 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.

Output:

  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)

Output:

       1

     /   \

  2        3

 / \      / \

4   5    6   7

Various other Operations that can be performed on trees are as follows:

  1. Check size of node: use root.size
  2. Check the height of node: use root.height
  3. Print list of nodes: use list(root)
  4. Check if balanced: root.is_balanced
  5. Leaf count: root.leaf_count
  6. Print levels of a tree: root.levels
  7. 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 :

  1. Inorder Traversal
  2. Postorder Traversal
  3. Preorder Traversal

>>Inorder Traversal: Left node, Root node, Right node

root.inorder

>>For Postorder Traversal: Left node, Right node, Root node

root.postorder

>>For Preorder Traversal: Root node, Left node, Right node

root.preorder

Leave a Reply