Given a Binary Tree, convert it to a Circular Doubly Linked List (In-Place).
- The left and right pointers in nodes are to be used as previous and next pointers respectively in converted Circular Linked List.
- The order of nodes in List must be same as Inorder of the given Binary Tree.
- The first node of Inorder traversal must be head node of the Circular List.
The idea can be described using below steps.
1) Write a general purpose function that concatenates two given circular doubly lists (This function is explained below).
2) Now traverse the given tree
….a) Recursively convert left subtree to a circular DLL. Let the converted list be leftList.
….a) Recursively convert right subtree to a circular DLL. Let the converted list be rightList.
….c) Make a circular linked list of root of the tree, make left and right of root to point to itself.
….d) Concatenate leftList with list of single root node.
….e) Concatenate the list produced in step above (d) with rightList.
Note that the above code traverses tree in Postorder fashion. We can traverse in inorder fashion also. We can first concatenate left subtree and root, then recur for right subtree and concatenate the result with left-root concatenation.
How to Concatenate two circular DLLs?
- Get the last node of the left list. Retrieving the last node is an O(1) operation, since the prev pointer of the head points to the last node of the list.
- Connect it with the first node of the right list
- Get the last node of the second list
- Connect it with the head of the list.
Below are implementations of above idea.
Circular Linked List is : 25 12 30 10 36 15
This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- Convert a given Binary Tree to Doubly Linked List | Set 3
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Convert a given Binary Tree to Doubly Linked List | Set 1
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Convert a Binary Tree into Doubly Linked List in spiral fashion
- Convert an Array to a Circular Doubly Linked List
- Extract Leaves of a Binary Tree in a Doubly Linked List
- Reverse a doubly circular linked list
- Doubly Circular Linked List | Set 2 (Deletion)
- Search an Element in Doubly Circular Linked List
- Doubly Circular Linked List | Set 1 (Introduction and Insertion)
- Insertion at Specific Position in a Circular Doubly Linked List
- Minimum swap required to convert binary tree to binary search tree
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)