Python program to convert a given binary tree to doubly linked list

PythonServer Side ProgrammingProgramming

When it is required to convert a given binary tree to a doubly linked list, a ‘Node’ class needs to be created. In this class, there are two attributes, the data that is present in the node, and the access to the next node of the linked list.

Another ‘linked_list’ class needs to be created that would have an initialization function, and the head of the node would be initialized to ‘None’.

In a doubly linked list, the nodes have pointers. The current node would have a pointer to the next node as well as the previous node. The last value in the list will have ‘NULL’ value in the next pointer. It can be traversed in both the directions.

Binary tree is a non-linear data structure, which contains one root node and every node except the root can have one parent node. A binary tree node can have atmost two childen.

Multiple methods are defined by the user to convert a given binary tree into a doubly linked list, and to print the node values.

Below is a demonstration for the same −


 Live Demo

class Node:
   def __init__(self, my_data):
      self.right = None = my_data
      self.left = None
class binary_tree_to_list:
   def __init__(self):
      self.root = None
      self.head = None
      self.tail = None
   def convert_tree_to_list(self, node_val):
      if node_val is None:
      if (self.head == None) :
         self.head = self.tail = node_val
         self.tail.right = node_val
         node_val.left = self.tail
         self.tail = node_val
   def print_it(self):
      curr = self.head
      if (self.head == None):
         print("The list is empty")
      print("The nodes are :")
      while curr != None:
         curr = curr.right
my_instance = binary_tree_to_list()
print("Elements are being added to the list")
my_instance.root = Node(10)
my_instance.root.left = Node(14)
my_instance.root.right = Node(17)
my_instance.root.left.left = Node(22)
my_instance.root.left.right = Node(29)
my_instance.root.right.left = Node(45)
my_instance.root.right.right = Node(80)


Elements are being added to the list
The nodes are :


  • The ‘Node’ class is created.
  • Another class with required attributes is created.
  • Another method named ‘convert_tree_to_list’ is defined, that is used to convert the given binary tree into a doubly linked list.
  • Another method named ‘print_it’ is defined, that displays the nodes of the circular linked list.
  • An object of the ‘binary_tree_to_list‘ class is created, and the methods are called on it to convert the tree to doubly linked list.
  • An ‘init’ method is defined, that the root, head, and tail nodes of the doubly linked list to None.
  • The ‘convert_tree_to_list’ method is called.
  • It iterates through the binary tree, and converts it into a doubly linked list.
  • This is displayed on the console using the ‘print_it’ method.
Published on 11-Mar-2021 16:05:44