Python program to convert a binary tree to a circular doubly link list.
Description:
To convert Binary tree into Doubly Linked List (DLL) we need to convert left and right subtrees to DLLs and maintan end of those lists. then, adjust the pointers.
Program:
defBSTToDLL(root):#main fuction to take the root of the BST and return the head of the doubly linked list
prev=None
head=None
BSTToDoublyList(root,prev,head)
return head
defBSTToDoublyList(root,prev,head):if(not root):return
BSTToDoublyList(root.left,prev,head)
#current nodes left points to previous node
root.left=prev
prev.right=root #previous nodes right points to current node
head=root # If previous is NULL that current node is head
right=root.right #Saving right node#Now we need to make list created till now as circular
head.left=root
root.right=head
#For right-subtree/parent, current node is inorder predecessor
prev=root
BSTToDoublyList(right,prev,head)
Comments