1
+ """
2
+ Binary trees are a type of data tree data structure in which a node can only have 0,1 or 2 children only.
3
+ Linked list is a type of linear data structure in which one object/node along with data, also contains the address of next object/node.
4
+ Doubly linked list is a type of linked list in which a node points to both the element before it, and after it.
5
+
6
+ A binary tree can be converted to a doubly linked list based on in order traversal, where left and right pointers point to prev and next element Eg :-
7
+
8
+ 10
9
+ / \
10
+ 12 15
11
+ /\ /
12
+ 25 30 36
13
+
14
+ can be converted to the doubly linked list
15
+
16
+ 25 <-> 12 <-> 30 <-> 10 <-> 36 <-> 15
17
+
18
+ We have used an iterative approach here, keeping the track of head and tail of the doubly linked list,
19
+ recursively solving left subtree, then redirecting the pointers to connect the last element and the current element,
20
+ and finally recursively solving the right subtree
21
+
22
+ """
23
+
24
+
25
+
26
+
27
+ class Node :
28
+ def __init__ (self , value ):
29
+ self .data = value
30
+ self .left = None
31
+ self .right = None
32
+
33
+ def binary_tree_to_dll (node , head , tail ):
34
+ if node == None :
35
+ return head , tail
36
+
37
+ head , tail = binary_tree_to_dll (node .left , head , tail )
38
+
39
+ if head == None :
40
+ head = node
41
+ else :
42
+ tail .right = node
43
+ node .left = tail
44
+ tail = node
45
+
46
+ head , tail = binary_tree_to_dll (node .right , head , tail )
47
+ return head , tail
48
+
49
+ def print_list (head ):
50
+ while head != None :
51
+ print (head .data , end = " " )
52
+ head = head .right
53
+
54
+
55
+ if __name__ == "__main__" :
56
+
57
+ root = Node (10 )
58
+ root .left = Node (12 )
59
+ root .right = Node (15 )
60
+ root .left .left = Node (25 )
61
+ root .left .right = Node (30 )
62
+ root .right .left = Node (36 )
63
+
64
+
65
+ head , tail = None , None
66
+ head , tail = binary_tree_to_dll (root , head , tail )
67
+ print ("\n Equivaltent doubly linked list : " , end = "" )
68
+ print_list (head )
69
+ print ("\n " )
70
+
71
+
72
+ """
73
+ root = Node(-5)
74
+ root.left = Node(10)
75
+ root.right = Node(2)
76
+
77
+ # ans : 10 -5 2
78
+ """
79
+
80
+ """
81
+ root = Node(3)
82
+ root.left = Node(5)
83
+ root.right = Node (7)
84
+ root.left.left = Node(9)
85
+ root.left.right = Node(11)
86
+ root.right.left = Node(13)
87
+ root.right.right = Node(15)
88
+ root.left.left.left = Node(17)
89
+
90
+ # ans : 17 9 5 11 3 13 7 15
91
+ """
0 commit comments