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 −
class Node: def __init__(self, my_data): self.right = None self.data = 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: return self.convert_tree_to_list(node_val.left) if (self.head == None) : self.head = self.tail = node_val else: self.tail.right = node_val node_val.left = self.tail self.tail = node_val self.convert_tree_to_list(node_val.right) def print_it(self): curr = self.head if (self.head == None): print("The list is empty") return print("The nodes are :") while curr != None: print(curr.data) 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) my_instance.convert_tree_to_list(my_instance.root) my_instance.print_it()
Elements are being added to the list The nodes are : 22 14 29 10 45 17 80