How to implement Binary Tree in Python

This Python tutorial helps you to understand what is Binary tree and how to implements Binary Tree in Python. First, we will learn what is Binary Tree.

Definition:- A tree in which every node can have a maximum of two children is called Binary Tree. Since each element has at most two children, we name them as the left child and right child.

A Binary Tree mainly consists of three parts. Those are:-

  1. Root or Data
  2. Left Child
  3. Right Child

Binary Tree is a non-linear data structure and has the following properties. Those are:-




  1. One node is always marked as the root node.
  2. Node other than the root node is associated with one parent node
  3. Every parent node can have a maximum of two children.

Advantages of Binary Tree

  1. Searching in Binary Tree becomes faster.
  2. Minimum and Maximum elements can be searched and picked up very easily.
  3. This data structure is used for graph traversals and to convert an expression to postfix and prefix forms.

 

                Algorithm for Binary Tree Insertion

When a node is inserted in Binary Tree, the new node always checks with its parent node. If the new node is less than the value of parent node, the new node will be placed on the left side of the parent otherwise the new node will be placed on the right side of the tree.

 

       Implementation of Binary Tree Insertion in Python

Source Code: Binary Tree in Python

class Tree:

    def __init__(self, data):

        self.left = None
        self.right = None
        self.data = data

    def insert(self, data):
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Tree(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Tree(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data

    def getTree(self):
        if self.left:
            self.left.getTree()
        print( self.data),
        if self.right:
            self.right.getTree()

root = Tree(20)
root.insert(11)
root.insert(25)
root.insert(10)
root.insert(30)
root.insert(19)

root.getTree()

Explanation :

  1. Create a class called Tree and initialize a constructor for passing the root value.
  2. Then create a function in the class called insert for taking new nodes as input.
  3. Now, the new input node checks with root value. The new input node 11 is less than 20, so it moves towards the left side of 20.
  4. Another new input node 25 is greater than 20, so it moves towards the right side of 20.

Output :

10 11 19 20 25 30

 

You can also read,


Leave a Reply

Your email address will not be published. Required fields are marked *