Binary Tree in Python

by

Posted on 02 September 2018

A Binary Tree can be defined as a tree with each node having at most two children, an empty tree is also a valid binary. Each node of the Binary tree consists of three main components

  • The data, this can be anything and it lies inside the node of a tree.
  • The left subtree.
  • The right subtree.

Also Read: Constructing a Binary Tree from Traversal Results

        a
       / \
      /   \
     /     \
    b       c
   / \     / \
  d   e   f   g
 /   / \     / \
h   i   j   k   l
       /
      m

A valid binary tree, each node consists of atmost two children.

In this tutorial, you will learn how to implement Binary tree using the Python programming language.  So let's create a class called Node and define the three main components of a node.

class Node(object):

    def __init__(self):
        self.left = None
        self.right = None
        self.value = None

Now let's write getters and setters function for each of the value.

class Node(object):

    def __init__(self):
        self.left = None
        self.right = None
        self.value = None
    @property
    def get_value(self):
        return self.value

    @property
    def get_left(self):
        return self.left

    @property
    def get_right(self):
        return self.right

    @get_left.setter
    def set_left(self, left_node):
        self.left = left_node

    @get_value.setter
    def set_value(self, value):
        self.value = value

    @get_right.setter
    def set_right(self, right_node):
        self.right = right_node

Now the one last this which is remaining is building the tree, we are going to define a function called create_tree() inside the Node class, which will create the objects of Node class and will assign the left and right subtrees using recursion, let's see the code for the create_tree() function.

def create_tree(self):
        _node = Node() #creating new node.
        _x = input("Enter the node data(-1 for null)")
        if(_x == str(-1)): #for defining no child.
            return None
        _node.set_value = _x #setting the value of the node.
        print("Enter the left child of {}".format(_x))
        _node.set_left = self.create_tree() #setting the left subtree.
        print("Enter the right child of {}".format(_x))
        _node.set_right = self.create_tree() #setting the right subtree.

        return _node

In the above function, every time the function create_tree() will be called a new node will be created and each time the value of the node and the left and right subtree will be defined.

Now we have completed our Node class, its time to use the class inside our driver function

if __name__ == '__main__':
    node = Node()
    root_node = node.create_tree()
    print(root_node.get_value) #will print the root node value

Now let's see the complete code for our Binary Tree in python.

class Node(object):

    def __init__(self):
        self.left = None
        self.right = None
        self.value = None
    @property
    def get_value(self):
        return self.value

    @property
    def get_left(self):
        return self.left

    @property
    def get_right(self):
        return self.right

    @get_left.setter
    def set_left(self, left_node):
        self.left = left_node
    @get_value.setter
    def set_value(self, value):
        self.value = value
    @get_right.setter
    def set_right(self, right_node):
        self.right = right_node


    def create_tree(self):
        _node = Node() #creating new node.
        _x = input("Enter the node data(-1 for null)")
        if(_x == str(-1)): #for defining no child.
            return None
        _node.set_value = _x #setting the value of the node.
        print("Enter the left child of {}".format(_x))
        _node.set_left = self.create_tree() #setting the left subtree.
        print("Enter the right child of {}".format(_x))
        _node.set_right = self.create_tree() #setting the right subtree.

        return _node


if __name__ == '__main__':
    node = Node()
    root_node = node.create_tree()
    print(root_node.get_value)

Output : 

Enter the node data(-1 for null)23
Enter the left child of 23
Enter the node data(-1 for null)-1
Enter the right child of 23
Enter the node data(-1 for null)12
Enter the left child of 12
Enter the node data(-1 for null)-1
Enter the right child of 12
Enter the node data(-1 for null)-1
23

We have successfully created our binary tree using python but wait you might be thinking we are just printing the root node of the tree what if we want to print the whole tree, for that we will learn the tree traversing techniques(preorder traversal, postorder traversal etc.) in the next tutorial, so stay tuned.


If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts

Search
Adverstisement
Adverstisement