The left and right pointers in nodes are to be used as previous and next pointers respectively in the converted Circular Linked List.
The order of nodes in the List must be the same as in Inorder for the given Binary Tree.
The first node of Inorder traversal must be the head node of the Circular List.
Examples:
Input: root = [1, 3, 2]
Output: 3 <-> 1 <-> 2
Explanation: The inorder traversal of the binary tree is 3, 1, 2. Therefore, the nodes are connected in the same order to form the Circular Doubly Linked List.
Input: root = [10, 20, 30, 40, 60]
Output: 40 <-> 20 <-> 60 <-> 10 <-> 30
Explanation: The inorder traversal of the binary tree is 40, 20, 60, 10, 30. Hence, the nodes are connected in this order to form the Circular Doubly Linked List.
[Expected Approach] Inorder Traversal using Previous Pointer - O(n) Time and O(h) Space
The idea is to perform an inorder traversal of the binary tree and connect each visited node with the previously visited node to form a Doubly Linked List.
Once the traversal is complete, connect the first and last nodes to make it circular.
Perform an inorder traversal of the binary tree.
Keep track of the first node as head and the previously visited node as prev.
For each visited node, if prev is nullptr, set head = root. Otherwise, connect the current node with prev by setting prev->right = root and root->left = prev. Then update prev = root.
Continue the inorder traversal by recursively processing the right subtree.
After the complete traversal, head points to the first node and prev points to the last node.
Connect the last node with the first node by setting prev->right = head and head->left = prev.
Return head as the head of the Circular Doubly Linked List.
Consider the following binary tree:
The inorder traversal of the tree is: 40 -> 20 -> 60 -> 10 -> 30
We process these nodes one by one and connect each node with the previously visited node.
For node 40, prev is nullptr, so set head = 40 and prev = 40.
For node 20, connect it with 40 and update prev = 20.
For node 60, connect it with 20 and update prev = 60.
For node 10, connect it with 60 and update prev = 10.
For node 30, connect it with 10 and update prev = 30.
After the inorder traversal, the Doubly Linked List is: 40 <-> 20 <-> 60 <-> 10 <-> 30
Here, head points to 40 and prev points to 30. To make the list circular, connect the last node with the first node:
prev->right = head
head->left = prev
The final Circular Doubly Linked List is:
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Convert Binary Tree to Circular Doubly Linked List.voidinorder(Node*root,Node*&head,Node*&prev){if(root==nullptr)return;// Recursively traverse the left subtree.inorder(root->left,head,prev);// Set the first node as head.if(prev==nullptr)head=root;else{// Connect the current node with the previous node.prev->right=root;root->left=prev;}// Update the previous node.prev=root;// Recursively traverse the right subtree.inorder(root->right,head,prev);}// Convert Binary Tree to Circular Doubly Linked List.Node*bTreeToCList(Node*root){if(root==nullptr)returnnullptr;Node*head=nullptr;Node*prev=nullptr;inorder(root,head,prev);// Connect the last node with the first node.prev->right=head;head->left=prev;returnhead;}// Display the circular doubly linked list.voiddisplay(Node*head){if(head==nullptr)return;Node*curr=head;do{cout<<curr->data;curr=curr->right;if(curr!=head)cout<<" <-> ";}while(curr!=head);cout<<endl;}intmain(){// Create the binary tree://// 10// / \ // 20 30// / \ // 40 60//// Inorder: 40 20 60 10 30Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->left=newNode(40);root->left->right=newNode(60);Node*head=bTreeToCList(root);display(head);return0;}
Java
classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=right=null;}}classGFG{// Convert Binary Tree to Circular Doubly Linked List.publicstaticvoidinorder(Noderoot,Node[]nodes){if(root==null)return;// Recursively traverse the left subtree.inorder(root.left,nodes);// Set the first node as head.if(nodes[1]==null)nodes[0]=root;else{// Connect the current node with the previous node.nodes[1].right=root;root.left=nodes[1];}// Update the previous node.nodes[1]=root;// Recursively traverse the right subtree.inorder(root.right,nodes);}// Convert Binary Tree to Circular Doubly Linked List.publicstaticNodebTreeToCList(Noderoot){if(root==null)returnnull;Node[]nodes=newNode[2];inorder(root,nodes);Nodehead=nodes[0];Nodeprev=nodes[1];// Connect the last node with the first node.prev.right=head;head.left=prev;returnhead;}// Display the circular doubly linked list.publicstaticvoiddisplay(Nodehead){if(head==null)return;Nodecurr=head;do{System.out.print(curr.data);curr=curr.right;if(curr!=head)System.out.print(" <-> ");}while(curr!=head);System.out.println();}publicstaticvoidmain(String[]args){// Create the binary tree://// 10// / \// 20 30// / \// 40 60//// Inorder: 40 20 60 10 30Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);Nodehead=bTreeToCList(root);display(head);}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Convert Binary Tree to Circular Doubly Linked List.definorder(root,pair):ifrootisNone:return# Recursively traverse the left subtree.inorder(root.left,pair)# Set the first node as head.ifpair[1]isNone:pair[0]=rootelse:# Connect the current node with the previous node.pair[1].right=rootroot.left=pair[1]# Update the previous node.pair[1]=root# Recursively traverse the right subtree.inorder(root.right,pair)# Convert Binary Tree to Circular Doubly Linked List.defbTreeToCList(root):ifrootisNone:returnNonehead=Noneprev=Nonepair=[head,prev]inorder(root,pair)head=pair[0]prev=pair[1]# Connect the last node with the first node.prev.right=headhead.left=prevreturnhead# Display the circular doubly linked list.defdisplay(head):ifheadisNone:returncurr=headwhileTrue:print(curr.data,end="")curr=curr.rightifcurr!=head:print(" <-> ",end="")else:breakprint()if__name__=="__main__":# Create the binary tree:## 10# / \# 20 30# / \# 40 60## Inorder: 40 20 60 10 30root=Node(10)root.left=Node(20)root.right=Node(30)root.left.left=Node(40)root.left.right=Node(60)head=bTreeToCList(root)display(head)
C#
usingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classGFG{// Convert Binary Tree to Circular Doubly Linked List.publicstaticvoidinorder(Noderoot,refNodehead,refNodeprev){if(root==null)return;// Recursively traverse the left subtree.inorder(root.left,refhead,refprev);// Set the first node as head.if(prev==null)head=root;else{// Connect the current node with the previous node.prev.right=root;root.left=prev;}// Update the previous node.prev=root;// Recursively traverse the right subtree.inorder(root.right,refhead,refprev);}// Convert Binary Tree to Circular Doubly Linked List.publicstaticNodebTreeToCList(Noderoot){if(root==null)returnnull;Nodehead=null;Nodeprev=null;inorder(root,refhead,refprev);// Connect the last node with the first node.prev.right=head;head.left=prev;returnhead;}// Display the circular doubly linked list.publicstaticvoiddisplay(Nodehead){if(head==null)return;Nodecurr=head;do{Console.Write(curr.data);curr=curr.right;if(curr!=head)Console.Write(" <-> ");}while(curr!=head);Console.WriteLine();}publicstaticvoidMain(){// Create the binary tree://// 10// / \// 20 30// / \// 40 60//// Inorder: 40 20 60 10 30Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);Nodehead=bTreeToCList(root);display(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Convert Binary Tree to Circular Doubly Linked List.functioninorder(root,pair){if(root===null)return;// Recursively traverse the left subtree.inorder(root.left,pair);// Set the first node as head.if(pair.prev===null)pair.head=root;else{// Connect the current node with the previous node.pair.prev.right=root;root.left=pair.prev;}// Update the previous node.pair.prev=root;// Recursively traverse the right subtree.inorder(root.right,pair);}// Convert Binary Tree to Circular Doubly Linked List.functionbTreeToCList(root){if(root===null)returnnull;lethead=null;letprev=null;letpair={head:head,prev:prev};inorder(root,pair);head=pair.head;prev=pair.prev;// Connect the last node with the first node.prev.right=head;head.left=prev;returnhead;}// Display the circular doubly linked list.functiondisplay(head){if(head===null)return;letcurr=head;do{process.stdout.write(curr.data.toString());curr=curr.right;if(curr!==head)process.stdout.write(" <-> ");}while(curr!==head);console.log();}// Driver code// Create the binary tree://// 10// / \// 20 30// / \// 40 60//// Inorder: 40 20 60 10 30letroot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);lethead=bTreeToCList(root);display(head);
Output
40 <-> 20 <-> 60 <-> 10 <-> 30
[Alternate Approach] Recursion and Concatenation - O(n) Time and O(h) Space
The idea is to recursively convert the left and right subtrees into Circular Doubly Linked Lists and concatenate them with the current node.
Recursively convert the left and right subtrees into CDLLs and store their heads in l and r.
Make the current node a single-node CDLL by setting its left and right pointers to itself.
Concatenate l with the current node, then concatenate the resulting list with r.
During concatenation, use the left pointer of each head to access the last node and connect the two circular lists in O(1) time.
Return the head of the combined CDLL.
Consider the binary tree:
The inorder traversal is: 40 20 60 10 30
The recursion first converts the left subtree: 40 <-> 20 <-> 60
The current node 10 is converted into a single-node CDLL: 10
Concatenating the left list with 10 gives: 40 <-> 20 <-> 60 <-> 10
Thus, the resulting CDLL follows the inorder order of the binary tree.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to concatenate two lists.Node*concatenate(Node*l,Node*r){if(l==nullptr)returnr;if(r==nullptr)returnl;// Store the last node of the left list.Node*ll=l->left;// Store the last node of the right list.Node*rl=r->left;// Connect the last node of the left list with the first node// of the right list.ll->right=r;r->left=ll;// Connect the first node with the last node.l->left=rl;rl->right=l;returnl;}// Function to convert binary tree into circular doubly linked list.Node*bTreeToCList(Node*root){if(root==nullptr)returnnullptr;// Recursively convert the left and right subtrees.Node*l=bTreeToCList(root->left);Node*r=bTreeToCList(root->right);// Make the current node a circular linked list of one node.root->left=root;root->right=root;// Concatenate the left list with the current node,// then concatenate the result with the right list.returnconcatenate(concatenate(l,root),r);}// Display the circular doubly linked list.voiddisplay(Node*head){if(head==nullptr)return;Node*cur=head;do{cout<<cur->data;cur=cur->right;if(cur!=head)cout<<" <-> ";}while(cur!=head);cout<<endl;}intmain(){// Create the binary tree://// 10// / \ // 20 30// / \ // 40 60//// Inorder: 40 20 60 10 30Node*root=newNode(10);root->left=newNode(20);root->right=newNode(30);root->left->left=newNode(40);root->left->right=newNode(60);Node*head=bTreeToCList(root);display(head);return0;}
Java
classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{// Function to concatenate two lists.staticNodeconcatenate(Nodel,Noder){if(l==null)returnr;if(r==null)returnl;// Store the last node of the left list.Nodell=l.left;// Store the last node of the right list.Noderl=r.left;// Connect the last node of the left list with the first node// of the right list.ll.right=r;r.left=ll;// Connect the first node with the last node.l.left=rl;rl.right=l;returnl;}staticNodebTreeToCList(Noderoot){if(root==null)returnnull;// Recursively convert the left and right subtrees.Nodel=bTreeToCList(root.left);Noder=bTreeToCList(root.right);// Make the current node a circular linked list of one node.root.left=root;root.right=root;// Concatenate the left list with the current node,// then concatenate the result with the right list.returnconcatenate(concatenate(l,root),r);}// Display the circular doubly linked list.staticvoiddisplay(Nodehead){if(head==null)return;Nodecur=head;do{System.out.print(cur.data);cur=cur.right;if(cur!=head)System.out.print(" <-> ");}while(cur!=head);System.out.println();}publicstaticvoidmain(String[]args){// Create the binary tree://// 10// / \// 20 30// / \// 40 60//// Inorder: 40 20 60 10 30Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);Nodehead=bTreeToCList(root);display(head);}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to concatenate two lists.defconcatenate(l,r):iflisNone:returnrifrisNone:returnl# Store the last node of the left list.ll=l.left# Store the last node of the right list.rl=r.left# Connect the last node of the left list with the first node# of the right list.ll.right=rr.left=ll# Connect the first node with the last node.l.left=rlrl.right=lreturnldefbTreeToCList(root):ifrootisNone:returnNone# Recursively convert the left and right subtrees.l=bTreeToCList(root.left)r=bTreeToCList(root.right)# Make the current node a circular linked list of one node.root.left=rootroot.right=root# Concatenate the left list with the current node,# then concatenate the result with the right list.returnconcatenate(concatenate(l,root),r)# Display the circular doubly linked list.defdisplay(head):ifheadisNone:returncur=headwhileTrue:print(cur.data,end="")cur=cur.rightifcur!=head:print(" <-> ",end="")else:breakprint()if__name__=="__main__":# Create the binary tree:## 10# / \# 20 30# / \# 40 60## Inorder: 40 20 60 10 30root=Node(10)root.left=Node(20)root.right=Node(30)root.left.left=Node(40)root.left.right=Node(60)head=bTreeToCList(root)display(head)
C#
usingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classGFG{// Function to concatenate two lists.publicstaticNodeconcatenate(Nodel,Noder){if(l==null)returnr;if(r==null)returnl;// Store the last node of the left list.Nodell=l.left;// Store the last node of the right list.Noderl=r.left;// Connect the last node of the left list with the first node// of the right list.ll.right=r;r.left=ll;// Connect the first node with the last node.l.left=rl;rl.right=l;returnl;}publicstaticNodebTreeToCList(Noderoot){if(root==null)returnnull;// Recursively convert the left and right subtrees.Nodel=bTreeToCList(root.left);Noder=bTreeToCList(root.right);// Make the current node a circular linked list of one node.root.left=root;root.right=root;// Concatenate the left list with the current node,// then concatenate the result with the right list.returnconcatenate(concatenate(l,root),r);}// Display the circular doubly linked list.publicstaticvoiddisplay(Nodehead){if(head==null)return;Nodecur=head;do{Console.Write(cur.data);cur=cur.right;if(cur!=head)Console.Write(" <-> ");}while(cur!=head);Console.WriteLine();}publicstaticvoidMain(){// Create the binary tree://// 10// / \// 20 30// / \// 40 60//// Inorder: 40 20 60 10 30Noderoot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);Nodehead=bTreeToCList(root);display(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to concatenate two lists.functionconcatenate(l,r){if(l===null)returnr;if(r===null)returnl;// Store the last node of the left list.letll=l.left;// Store the last node of the right list.letrl=r.left;// Connect the last node of the left list with the first// node of the right list.ll.right=r;r.left=ll;// Connect the first node with the last node.l.left=rl;rl.right=l;returnl;}functionbTreeToCList(root){if(root===null)returnnull;// Recursively convert the left and right subtrees.letl=bTreeToCList(root.left);letr=bTreeToCList(root.right);// Make the current node a circular linked list of one// node.root.left=root;root.right=root;// Concatenate the left list with the current node,// then concatenate the result with the right list.returnconcatenate(concatenate(l,root),r);}// Display the circular doubly linked list.functiondisplay(head){if(head===null)return;letcur=head;letans="";do{ans+=cur.data;cur=cur.right;if(cur!==head)ans+=" <-> ";}while(cur!==head);console.log(ans);}// Driver code// Create the binary tree://// 10// / \// 20 30// / \// 40 60//// Inorder: 40 20 60 10 30letroot=newNode(10);root.left=newNode(20);root.right=newNode(30);root.left.left=newNode(40);root.left.right=newNode(60);lethead=bTreeToCList(root);display(head);