Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
C++ Program For Rearranging A Given Linked List In-Place
Next article icon

Convert Binary Tree to Circular Doubly Linked List using Linear extra space

Last Updated : 28 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree, convert it to a Circular Doubly Linked List. 

  • 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 the order of the given Binary Tree.
  • The first node of Inorder traversal must be the head node of the Circular List.

Example: 

An in-place solution to this problem is discussed in the previous post.
In this post, a much simpler solution, but using extra O(n) space, is discussed.
In this approach, first, we do an In-Order traversal of the given binary tree, we store this traversal in a vector, which will be passed on to the function along with the tree. Now, generate a circular doubly linked list from the elements of the vector. 
To generate a circular doubly linked list from the vector, make the first element of the vector as the head of the linked list and also create a current pointer that is right now pointing to the head. Now start traversing the array from the second element and do the following. 

  1. Create a temporary pointer that points to the current pointer.
  2. Make a new node with the current element of the vector.
  3. Make the current right point to this new node.
  4. Make the current pointer the current right pointer.
  5. Now, finally, the current left point is a temporary pointer created in the first step.

Do this for all the elements and after the traversal is completed, make the current’s right (current is right now pointing to the last element of the vector) point to the head of the list and make the head’s left point to the current pointer. Finally, return the head.

Below is the implementation of the above approach: 

C++




// A C++ program for conversion
// of Binary Tree to CDLL
  
#include <bits/stdc++.h>
using namespace std;
  
// A binary tree node has data,
// and left and right pointers
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
  
    Node(int x)
    {
        data = x;
        left = right = NULL;
    }
};
  
// Function to perform In-Order traversal of the
// tree and store the nodes in a vector
void inorder(Node* root, vector<int>& v)
{
    if (!root)
        return;
  
    /* first recur on left child */
    inorder(root->left, v);
  
    /* append the data of node in vector */
    v.push_back(root->data);
  
    /* now recur on right child */
    inorder(root->right, v);
}
  
// Function to convert Binary Tree to Circular
// Doubly Linked list using the vector which stores
// In-Order traversal of the Binary Tree
Node* bTreeToCList(Node* root)
{
    // Base cases
    if (root == NULL)
        return NULL;
  
    // Vector to be used for storing the nodes
    // of tree in In-order form
    vector<int> v;
  
    // Calling the In-Order traversal function
    inorder(root, v);
  
    // Create the head of the linked list pointing
    // to the root of the tree
    Node* head_ref = new Node(v[0]);
  
    // Create a current pointer to be used in traversal
    Node* curr = head_ref;
  
    // Traversing the nodes of the tree starting
    // from the second elements
    for (int i = 1; i < v.size(); i++) {
  
        // Create a temporary pointer
        // pointing to current
        Node* temp = curr;
  
        // Current's right points to the current
        // node in traversal
        curr->right = new Node(v[i]);
  
        // Current points to its right
        curr = curr->right;
  
        // Current's left points to temp
        curr->left = temp;
    }
  
    // Current's right points to head of the list
    curr->right = head_ref;
  
    // Head's left points to current
    head_ref->left = curr;
  
    // Return head of the list
    return head_ref;
}
  
// Display Circular Link List
void displayCList(Node* head)
{
    cout << "Circular Doubly Linked List is :\n";
  
    Node* itr = head;
    do {
        cout << itr->data << " ";
        itr = itr->right;
    } while (head != itr);
  
    cout << "\n";
}
  
// Driver Code
int main()
{
    Node* root = new Node(10);
    root->left = new Node(12);
    root->right = new Node(15);
    root->left->left = new Node(25);
    root->left->right = new Node(30);
    root->right->left = new Node(36);
  
    Node* head = bTreeToCList(root);
    displayCList(head);
  
    return 0;
}
 
 

Java




// Java program for conversion
// of Binary Tree to CDLL
import java.util.*;
class GFG 
{
  
// A binary tree node has data,
// and left and right pointers
static class Node
{  
    int data;
    Node left;
    Node right;
  
    Node(int x)
    {
        data = x;
        left = right = null;
    }
};
  
// Function to perform In-Order traversal of the
// tree and store the nodes in a vector
static void inorder(Node root, Vector<Integer> v)
{
    if (root == null)
        return;
  
    /* first recur on left child */
    inorder(root.left, v);
  
    /* append the data of node in vector */
    v.add(root.data);
  
    /* now recur on right child */
    inorder(root.right, v);
}
  
// Function to convert Binary Tree to Circular
// Doubly Linked list using the vector which stores
// In-Order traversal of the Binary Tree
static Node bTreeToCList(Node root)
{
    // Base cases
    if (root == null)
        return null;
  
    // Vector to be used for storing the nodes
    // of tree in In-order form
    Vector<Integer> v = new Vector<>();
  
    // Calling the In-Order traversal function
    inorder(root, v);
  
    // Create the head of the linked list pointing
    // to the root of the tree
    Node head_ref = new Node(v.get(0));
  
    // Create a current pointer to be used in traversal
    Node curr = head_ref;
  
    // Traversing the nodes of the tree starting
    // from the second elements
    for (int i = 1; i < v.size(); i++) 
    {
  
        // Create a temporary pointer
        // pointing to current
        Node temp = curr;
  
        // Current's right points to the current
        // node in traversal
        curr.right = new Node(v.get(i));
  
        // Current points to its right
        curr = curr.right;
  
        // Current's left points to temp
        curr.left = temp;
    }
  
    // Current's right points to head of the list
    curr.right = head_ref;
  
    // Head's left points to current
    head_ref.left = curr;
  
    // Return head of the list
    return head_ref;
}
  
// Display Circular Link List
static void displayCList(Node head)
{
    System.out.println("Circular Doubly Linked List is :");
  
    Node itr = head;
    do 
    {
        System.out.print(itr.data + " ");
        itr = itr.right;
    } while (head != itr);
  
    System.out.println();
}
  
// Driver Code
public static void main(String[] args)
{
    Node root = new Node(10);
    root.left = new Node(12);
    root.right = new Node(15);
    root.left.left = new Node(25);
    root.left.right = new Node(30);
    root.right.left = new Node(36);
  
    Node head = bTreeToCList(root);
    displayCList(head);
}
}
  
// This code is contributed by Rajput-Ji
 
 

Python




# Python program for conversion
# of Binary Tree to CDLL
  
# A binary tree node has data,
# and left and right pointers
class Node: 
    def __init__(self, data): 
        self.data = data 
        self.left = self.right = None
  
v = []
  
# Function to perform In-Order traversal of the
# tree and store the nodes in a vector
def inorder(root):
    global v
      
    if (root == None):
        return
  
    # first recur on left child 
    inorder(root.left)
  
    # append the data of node in vector 
    v.append(root.data)
  
    # now recur on right child 
    inorder(root.right)
  
# Function to convert Binary Tree to Circular
# Doubly Linked list using the vector which stores
# In-Order traversal of the Binary Tree
def bTreeToCList(root):
  
    global v
      
    # Base cases
    if (root == None):
        return None
  
    # Vector to be used for storing the nodes
    # of tree in In-order form
    v = []
  
    # Calling the In-Order traversal function
    inorder(root)
  
    # Create the head of the linked list pointing
    # to the root of the tree
    head_ref = Node(v[0])
  
    # Create a current pointer to be used in traversal
    curr = head_ref
  
    i = 1
      
    # Traversing the nodes of the tree starting
    # from the second elements
    while ( i < len(v)) :
      
          
        # Create a temporary pointer
        # pointing to current
        temp = curr
  
        # Current's right points to the current
        # node in traversal
        curr.right = Node(v[i])
  
        # Current points to its right
        curr = curr.right
  
        # Current's left points to temp
        curr.left = temp
        i = i + 1
  
    # Current's right points to head of the list
    curr.right = head_ref
  
    # Head's left points to current
    head_ref.left = curr
  
    # Return head of the list
    return head_ref
  
# Display Circular Link List
def displayCList(head):
  
    print("Circular Doubly Linked List is :", end = "")
  
    itr = head
    while(True):
        print(itr.data, end = " ")
        itr = itr.right
        if(head == itr):
            break
  
    print()
  
# Driver Code
root = Node(10)
root.left = Node(12)
root.right = Node(15)
root.left.left = Node(25)
root.left.right = Node(30)
root.right.left = Node(36)
  
head = bTreeToCList(root)
displayCList(head)
  
# This code is contributed by Arnab Kundu
 
 

C#




// C# program for conversion
// of Binary Tree to CDLL
using System;
using System.Collections.Generic;
  
class GFG 
{
  
// A binary tree node has data,
// and left and right pointers
public class Node
{ 
    public int data;
    public Node left;
    public Node right;
  
    public Node(int x)
    {
        data = x;
        left = right = null;
    }
};
  
// Function to perform In-Order traversal of the
// tree and store the nodes in a vector
static void inorder(Node root, List<int> v)
{
    if (root == null)
        return;
  
    /* first recur on left child */
    inorder(root.left, v);
  
    /* append the data of node in vector */
    v.Add(root.data);
  
    /* now recur on right child */
    inorder(root.right, v);
}
  
// Function to convert Binary Tree to Circular
// Doubly Linked list using the vector which stores
// In-Order traversal of the Binary Tree
static Node bTreeToCList(Node root)
{
    // Base cases
    if (root == null)
        return null;
  
    // Vector to be used for storing the nodes
    // of tree in In-order form
    List<int> v = new List<int>();
  
    // Calling the In-Order traversal function
    inorder(root, v);
  
    // Create the head of the linked list 
    // pointing to the root of the tree
    Node head_ref = new Node(v[0]);
  
    // Create a current pointer 
    // to be used in traversal
    Node curr = head_ref;
  
    // Traversing the nodes of the tree starting
    // from the second elements
    for (int i = 1; i < v.Count; i++) 
    {
  
        // Create a temporary pointer
        // pointing to current
        Node temp = curr;
  
        // Current's right points to the current
        // node in traversal
        curr.right = new Node(v[i]);
  
        // Current points to its right
        curr = curr.right;
  
        // Current's left points to temp
        curr.left = temp;
    }
  
    // Current's right points to head of the list
    curr.right = head_ref;
  
    // Head's left points to current
    head_ref.left = curr;
  
    // Return head of the list
    return head_ref;
}
  
// Display Circular Link List
static void displayCList(Node head)
{
    Console.WriteLine("Circular Doubly " +
                      "Linked List is :");
  
    Node itr = head;
    do
    {
        Console.Write(itr.data + " ");
        itr = itr.right;
    } while (head != itr);
  
    Console.WriteLine();
}
  
// Driver Code
public static void Main(String[] args)
{
    Node root = new Node(10);
    root.left = new Node(12);
    root.right = new Node(15);
    root.left.left = new Node(25);
    root.left.right = new Node(30);
    root.right.left = new Node(36);
  
    Node head = bTreeToCList(root);
    displayCList(head);
}
}
  
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
// javascript program for conversion
// of Binary Tree to CDLL
  
// A binary tree node has data,
// and left and right pointers
    class Node {
        constructor(val) {
            this.data = val;
            this.left = null;
            this.right = null;
        }
    }
  
    // Function to perform In-Order traversal of the
    // tree and store the nodes in a vector
    function inorder(root, v) {
        if (root == null)
            return;
  
        /* first recur on left child */
        inorder(root.left, v);
  
        /* append the data of node in vector */
        v.push(root.data);
  
        /* now recur on right child */
        inorder(root.right, v);
    }
  
    // Function to convert Binary Tree to Circular
    // Doubly Linked list using the vector which stores
    // In-Order traversal of the Binary Tree
    function bTreeToCList(root) {
        // Base cases
        if (root == null)
            return null;
  
        // Vector to be used for storing the nodes
        // of tree in In-order form
        var v = [];
  
        // Calling the In-Order traversal function
        inorder(root, v);
  
        // Create the head of the linked list pointing
        // to the root of the tree
        var head_ref = new Node(v[0]);
  
        // Create a current pointer to be used in traversal
        var curr = head_ref;
  
        // Traversing the nodes of the tree starting
        // from the second elements
        for (i = 1; i < v.length; i++) {
  
            // Create a temporary pointer
            // pointing to current
            var temp = curr;
  
            // Current's right points to the current
            // node in traversal
            curr.right = new Node(v[i]);
  
            // Current points to its right
            curr = curr.right;
  
            // Current's left points to temp
            curr.left = temp;
        }
  
        // Current's right points to head of the list
        curr.right = head_ref;
  
        // Head's left points to current
        head_ref.left = curr;
  
        // Return head of the list
        return head_ref;
    }
  
    // Display Circular Link List
    function displayCList(head) {
        document.write("Circular Doubly Linked List is :<br/>");
  
        var itr = head;
        do {
            document.write(itr.data + " ");
            itr = itr.right;
        } while (head != itr);
  
        document.write();
    }
  
    // Driver Code
      
    var root = new Node(10);
    root.left = new Node(12);
    root.right = new Node(15);
    root.left.left = new Node(25);
    root.left.right = new Node(30);
    root.right.left = new Node(36);
  
    var head = bTreeToCList(root);
    displayCList(head);
  
// This code contributed by Rajput-Ji
</script>
 
 
Output: 
Circular Doubly Linked List is :  25 12 30 10 36 15

 

Time Complexity: O(N), where N is the number of nodes in the Binary Tree. 
Auxiliary Space: O(N)
 



Next Article
C++ Program For Rearranging A Given Linked List In-Place

A

Abhishek_Vashisht
Improve
Article Tags :
  • C++ Programs
  • DSA
  • Linked List
  • Tree
  • Binary Tree
  • circular linked list
Practice Tags :
  • circular linked list
  • Linked List
  • Tree

Similar Reads

  • Print leaf nodes in binary tree from left to right using one stack
    Given a binary tree, the task is to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 4 5 6 7 Input : 4 / \ 5 9 / \ / \ 8 3 7 2 / /
    8 min read
  • Flatten a binary tree into linked list | Set-2
    Given a binary tree, flatten it into a linked list. After flattening, the left of each node should point to NULL and right should contain next node in level order. Example: Input: 1 / \ 2 5 / \ \ 3 4 6 Output: 1 \ 2 \ 3 \ 4 \ 5 \ 6 Input: 1 / \ 3 4 / 2 \ 5 Output: 1 \ 3 \ 4 \ 2 \ 5 Approach: An appr
    9 min read
  • C++ Program For Rearranging A Given Linked List In-Place
    Given a singly linked list L0 -> L1 -> … -> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 -
    7 min read
  • Flatten a binary tree into linked list
    Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder. Examples: Input : 1 / \ 2 5 / \ \ 3 4 6Output : 1 \ 2 \ 3 \ 4 \ 5 \ 6Input : 1 / \ 3 4
    15+ min read
  • Menu Driven Program to implement all the operations of Doubly Circular Linked List
    Circular Doubly Linked List has properties of both Doubly Linked List and Circular Linked List in which two consecutive elements are linked or connected by previous and next pointer and the last node points to the first node by next pointer and also the first node points to the last node by the prev
    15+ min read
  • Print nodes in top view of Binary Tree | Set 2
    Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right. Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance
    14 min read
  • Print the longest path from root to leaf in a Binary tree
    Given a binary tree, the task is to print the longest path from the root node to the leaf node. If there are multiple answers print any one of them. Examples: Input: 4 / \ 3 6 / \ 5 7 Output: 4 -> 6 -> 7 Explanation: Longest paths from root to leaf are (4 -> 6 -> 5) and (4 -> 6 ->
    8 min read
  • C++ Program to Rotate Doubly linked list by N nodes
    Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d As
    4 min read
  • Connect all nodes to their Left Neighbors in a Binary Tree
    Given a Binary Tree, where each node contains an extra empty pointer initially null. The task is to connect all nodes of the binary tree to their left neighbor at the same level using this extra pointer.Examples: Input : A / \ B C / \ \ D E F Output : NULL<--A / \ NULL<--B<--C / \ \ NULL
    10 min read
  • Print all leaf nodes of an n-ary tree using DFS
    Given an array edge[][2] where (edge[i][0], edge[i][1]) defines an edge in the n-ary tree, the task is to print all the leaf nodes of the given tree using. Examples: Input: edge[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}} Output: 4 5 6 1 / \ 2 3 / \ \ 4 5 6 Input: edge[][] = {{1, 5}, {1, 7}, {5,
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences