Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
bz2 Module in Python
Next article icon

Binarytree Module in Python

Last Updated : 10 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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)
  
# Getting binary tree
print('Binary tree :', root)
  
# Getting list of nodes
print('List of nodes :', list(root))
  
# Getting inorder of nodes
print('Inorder of nodes :', root.inorder)
  
# Checking tree properties
print('Size of tree :', root.size)
print('Height of tree :', root.height)
  
# Get all properties at once
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




# Creating binary tree 
# from given list
from binarytree import build
  
  
# List of nodes
nodes =[3, 6, 8, 2, 11, None, 13]
  
# Building the binary tree
binary_tree = build(nodes)
print('Binary tree from list :\n',
      binary_tree)
  
# Getting list of nodes from
# binarytree
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
  
  
# Create a random binary 
# tree of any height
root = tree()
print("Binary tree of any height :")
print(root)
  
# Create a random binary 
# tree of given height
root2 = tree(height = 2)
print("Binary tree of given height :")
print(root2)
  
# Create a random perfect 
# binary tree of given height
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
  
  
# Create a random BST 
# of any height
root = bst()
print('BST of any height : \n',
      root)
  
# Create a random BST of 
# given height
root2 = bst(height = 2)
print('BST of given height : \n',
      root2)
  
# Create a random perfect 
# BST of given height
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 – 

  • max heap 
  • min heap 
     

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
  
  
# Create a random max-heap
root = heap()
print('Max-heap of any height : \n',
      root)
  
# Create a random max-heap
# of given height
root2 = heap(height = 2)
  
print('Max-heap of given height : \n',
      root2)
  
# Create a random perfect 
# min-heap of given height
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


Next Article
bz2 Module in Python

N

naina024
Improve
Article Tags :
  • Python
  • Binary Tree
  • Python-DSA
  • python-modules
Practice Tags :
  • python

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. I
    4 min read
  • bz2 Module in Python
    bz2 module in Python provides support for compressing and decompressing data using the bzip2 compression algorithm. It allows handling .bz2 files and compressing / decompressing byte data efficiently. For example: [GFGTABS] Python import bz2 # Data to compress s = b"Hello, BZ2 Compression!
    2 min read
  • Cmdparse module in Python
    The Class which provides a simple framework for writing line-oriented command interpreters is called cmd class. These are often useful for administrative tools, prototypes and test harnesses that will later be wrapped in a more sophisticated interface. The command-line interface can be easily made u
    6 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
  • File Mode in Python
    In Python, the file mode specifies the purpose and the operations that can be performed on a file when it is opened. When you open a file using the open() function, you can specify the file mode as the second argument. Different File Mode in PythonBelow are the different types of file modes in Pytho
    5 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences