Python Program to Implement Binary Tree using Linked List


When it is required to implement a binary tree data structure using a linked list, a method to set the root node, a method to perform in-order traversal, to insert element to the left of the root node, a method to insert element to the right of the root node, and a method to search the values are defined.

Below is a demonstration for the same −

Example

 Live Demo

class BinaryTree_structure:
   def __init__(self, key=None):
      self.key = key
      self.left = None
      self.right = None

   def set_root(self, key):
      self.key = key

   def in_order_traversal(self):
      if self.left is not None:
         self.left.in_order_traversal()
      print(self.key, end=' ')
      if self.right is not None:
         self.right.in_order_traversal()

   def insert_left(self, new_node):
      self.left = new_node

   def insert_right(self, new_node):
      self.right = new_node

   def search_val(self, key):
      if self.key == key:
         return self
      if self.left is not None:
         temp = self.left.search_val(key)
         if temp is not None:
            return temp
      if self.right is not None:
         temp = self.right.search_val(key)
         return temp
      return None

btree = None

print('Menu (this assumes no duplicate keys)')
print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('quit')

while True:
   print('The inorder traversal of binary tree ', end='')
   if btree is not None:
      btree.in_order_traversal()
   print()

   do = input('What would you like to do? ').split()

   operation = do[0].strip().lower()
   if operation == 'insert':
      data = int(do[1])
      new_node = BinaryTree_structure(data)
      sub_op = do[2].strip().lower()
      if sub_op == 'at':
         btree = new_node
      else:
         position = do[4].strip().lower()
         key = int(position)
         ref_node = None
         if btree is not None:
            ref_node = btree.search_val(key)
         if ref_node is None:
            print('No such key exists')
            continue
         if sub_op == 'left':
            ref_node.insert_left(new_node)
         elif sub_op == 'right':
            ref_node.insert_right(new_node)
      elif operation == 'quit':
         break

Output

Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
quit
The inorder traversal of binary tree
What would you like to do? insert 45 at root
The inorder traversal of binary tree 45
What would you like to do? insert 78 left of 45
The inorder traversal of binary tree 78 45
What would you like to do? insert 90 right of 45
The inorder traversal of binary tree 78 45 90
What would you like to do? quit

Explanation

  • The ‘BinaryTree_structure’ class is created.

  • It has a ‘set_root’ function that helps set the root value for the Tree.

  • A method named ‘in_order_traversal’ is defined, that helps traverse through the tree in ‘Left->Node->Right’ order.

  • Another method named ‘insert_left’ is defined, that helps add an element to the left of the root value.

  • Another method named ‘insert_right’ is defined, that helps add an element to the right of the root value.

  • Another method named ‘search_val’ is defined, that helps delete a value from the top of the stack, and returns the deleted value.

  • Four options are given, such as ‘insert at root’, ‘insert to left of’, ‘insert to right of’ and ‘quit’.

  • Based on the input/choice by user, the respective operations are performed.

  • This output is displayed on the console.

Updated on: 14-Apr-2021

370 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements