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:
Convert Ternary Expression to a Binary Tree
Next article icon

Convert a Binary Tree to a Circular Doubly Link List

Last Updated : 10 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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 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:

tree to list

Recommended Practice
Binary Tree to CDLL
Try It!

Convert a Binary Tree to a Circular Doubly Link List using Recursion:

The idea is to make a general-purpose function that concatenates two given circular doubly lists

Follow the steps below to solve the problem:

  • Recursively convert the left subtree to a circular DLL. Let the converted list be leftList.
  • Recursively convert the right subtree to a circular DLL. Let the converted list be rightList. 
  • Make a circular linked list of roots of the tree, and make the left and right root points to themselves. 
  • Concatenate leftList with the list of the single root node. 
  • Concatenate the list produced in the step above with rightList.

Note: The above approach traverses the tree in a Postorder fashion. We can traverse in an inorder fashion also. We can first concatenate left subtree and root, then recur for the right subtree and concatenate the result with left-root concatenation.

How do 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 the above idea:

C++




// C++ Program to convert a Binary Tree
// to a Circular Doubly Linked List
#include <iostream>
using namespace std;
  
// To represents a node of a Binary Tree
struct Node {
    struct Node *left, *right;
    int data;
};
  
// A function that appends rightList at the end
// of leftList.
Node* concatenate(Node* leftList, Node* rightList)
{
    // If either of the list is empty
    // then return the other list
    if (leftList == NULL)
        return rightList;
    if (rightList == NULL)
        return leftList;
  
    // Store the last Node of left List
    Node* leftLast = leftList->left;
  
    // Store the last Node of right List
    Node* rightLast = rightList->left;
  
    // Connect the last node of Left List
    // with the first Node of the right List
    leftLast->right = rightList;
    rightList->left = leftLast;
  
    // Left of first node points to
    // the last node in the list
    leftList->left = rightLast;
  
    // Right of last node refers to the first
    // node of the List
    rightLast->right = leftList;
  
    return leftList;
}
  
// Function converts a tree to a circular Linked List
// and then returns the head of the Linked List
Node* bTreeToCList(Node* root)
{
    if (root == NULL)
        return NULL;
  
    // Recursively convert left and right subtrees
    Node* left = bTreeToCList(root->left);
    Node* right = bTreeToCList(root->right);
  
    // Make a circular linked list of single node
    // (or root). To do so, make the right and
    // left pointers of this node point to itself
    root->left = root->right = root;
  
    // Step 1 (concatenate the left list with the list
    //         with single node, i.e., current node)
    // Step 2 (concatenate the returned list with the
    //         right List)
    return concatenate(concatenate(left, root), right);
}
  
// Display Circular Link List
void displayCList(Node* head)
{
    cout << "Circular Linked List is :\n";
    Node* itr = head;
    do {
        cout << itr->data << " ";
        itr = itr->right;
    } while (head != itr);
    cout << "\n";
}
  
// Create a new Node and return its address
Node* newNode(int data)
{
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
  
// Driver Program to test above function
int main()
{
    Node* root = newNode(10);
    root->left = newNode(12);
    root->right = newNode(15);
    root->left->left = newNode(25);
    root->left->right = newNode(30);
    root->right->left = newNode(36);
  
    Node* head = bTreeToCList(root);
    displayCList(head);
  
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

C




// C Program to convert a Binary Tree
// to a Circular Doubly Linked List
#include <stdio.h>
#include <stdlib.h>
  
// To represents a node of a Binary Tree
typedef struct Node {
    struct Node *left, *right;
    int data;
} Node;
  
// A function that appends rightList at the end
// of leftList.
Node* concatenate(Node* leftList, Node* rightList)
{
    // If either of the list is empty
    // then return the other list
    if (leftList == NULL)
        return rightList;
    if (rightList == NULL)
        return leftList;
  
    // Store the last Node of left List
    Node* leftLast = leftList->left;
  
    // Store the last Node of right List
    Node* rightLast = rightList->left;
  
    // Connect the last node of Left List
    // with the first Node of the right List
    leftLast->right = rightList;
    rightList->left = leftLast;
  
    // Left of first node points to
    // the last node in the list
    leftList->left = rightLast;
  
    // Right of last node refers to the first
    // node of the List
    rightLast->right = leftList;
  
    return leftList;
}
  
// Function converts a tree to a circular Linked List
// and then returns the head of the Linked List
Node* bTreeToCList(Node* root)
{
    if (root == NULL)
        return NULL;
  
    // Recursively convert left and right subtrees
    Node* left = bTreeToCList(root->left);
    Node* right = bTreeToCList(root->right);
  
    // Make a circular linked list of single node
    // (or root). To do so, make the right and
    // left pointers of this node point to itself
    root->left = root->right = root;
  
    // Step 1 (concatenate the left list with the list
    //         with single node, i.e., current node)
    // Step 2 (concatenate the returned list with the
    //         right List)
    return concatenate(concatenate(left, root), right);
}
  
// Display Circular Link List
void displayCList(Node* head)
{
    printf("Circular Linked List is :\n");
    Node* itr = head;
    do {
        printf("%d ", itr->data);
        itr = itr->right;
    } while (head != itr);
    printf("\n");
}
  
// Create a new Node and return its address
Node* newNode(int data)
{
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
  
// Driver Program to test above function
int main()
{
    Node* root = newNode(10);
    root->left = newNode(12);
    root->right = newNode(15);
    root->left->left = newNode(25);
    root->left->right = newNode(30);
    root->right->left = newNode(36);
  
    Node* head = bTreeToCList(root);
    displayCList(head);
  
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

Java




// Java Program to convert a Binary Tree to a
// Circular Doubly Linked List
  
// Node class represents a Node of a Tree
class Node {
    int val;
    Node left, right;
  
    public Node(int val)
    {
        this.val = val;
        left = right = null;
    }
}
  
// A class to represent a tree
class Tree {
    Node root;
    public Tree() { root = null; }
  
    // concatenate both the lists and returns the head
    // of the List
    public Node concatenate(Node leftList, Node rightList)
    {
        // If either of the list is empty, then
        // return the other list
        if (leftList == null)
            return rightList;
        if (rightList == null)
            return leftList;
  
        // Store the last Node of left List
        Node leftLast = leftList.left;
  
        // Store the last Node of right List
        Node rightLast = rightList.left;
  
        // Connect the last node of Left List
        // with the first Node of the right List
        leftLast.right = rightList;
        rightList.left = leftLast;
  
        // left of first node refers to
        // the last node in the list
        leftList.left = rightLast;
  
        // Right of last node refers to the first
        // node of the List
        rightLast.right = leftList;
  
        // Return the Head of the List
        return leftList;
    }
  
    // Method converts a tree to a circular
    // Link List and then returns the head
    // of the Link List
    public Node bTreeToCList(Node root)
    {
        if (root == null)
            return null;
  
        // Recursively convert left and right subtrees
        Node left = bTreeToCList(root.left);
        Node right = bTreeToCList(root.right);
  
        // Make a circular linked list of single node
        // (or root). To do so, make the right and
        // left pointers of this node point to itself
        root.left = root.right = root;
  
        // Step 1 (concatenate the left list with the list
        //         with single node, i.e., current node)
        // Step 2 (concatenate the returned list with the
        //         right List)
        return concatenate(concatenate(left, root), right);
    }
  
    // Display Circular Link List
    public void display(Node head)
    {
        System.out.println("Circular Linked List is :");
        Node itr = head;
        do {
            System.out.print(itr.val + " ");
            itr = itr.right;
        } while (itr != head);
        System.out.println();
    }
}
  
// Driver Code
class Main {
    public static void main(String args[])
    {
        // Build the tree
        Tree tree = new Tree();
        tree.root = new Node(10);
        tree.root.left = new Node(12);
        tree.root.right = new Node(15);
        tree.root.left.left = new Node(25);
        tree.root.left.right = new Node(30);
        tree.root.right.left = new Node(36);
  
        // head refers to the head of the Link List
        Node head = tree.bTreeToCList(tree.root);
  
        // Display the Circular LinkedList
        tree.display(head);
    }
}
 
 

Python3




# Python3 Program to convert a Binary
# Tree to a Circular Doubly Linked List
  
  
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
  
# A function that appends rightList
# at the end of leftList.
  
  
def concatenate(leftList, rightList):
  
    # If either of the list is empty
    # then return the other list
    if (leftList == None):
        return rightList
    if (rightList == None):
        return leftList
  
    # Store the last Node of left List
    leftLast = leftList.left
  
    # Store the last Node of right List
    rightLast = rightList.left
  
    # Connect the last node of Left List
    # with the first Node of the right List
    leftLast.right = rightList
    rightList.left = leftLast
  
    # Left of first node points to
    # the last node in the list
    leftList.left = rightLast
  
    # Right of last node refers to
    # the first node of the List
    rightLast.right = leftList
  
    return leftList
  
# Function converts a tree to a circular
# Linked List and then returns the head
# of the Linked List
  
  
def bTreeToCList(root):
    if (root == None):
        return None
  
    # Recursively convert left and
    # right subtrees
    left = bTreeToCList(root.left)
    right = bTreeToCList(root.right)
  
    # Make a circular linked list of single
    # node (or root). To do so, make the
    # right and left pointers of this node
    # point to itself
    root.left = root.right = root
  
    # Step 1 (concatenate the left list
    #          with the list with single
    #         node, i.e., current node)
    # Step 2 (concatenate the returned list
    #          with the right List)
    return concatenate(concatenate(left,
                                   root), right)
  
# Display Circular Link List
  
  
def displayCList(head):
    print("Circular Linked List is :")
    itr = head
    first = 1
    while (head != itr or first):
        print(itr.data, end=" ")
        itr = itr.right
        first = 0
    print()
  
  
# Driver Code
if __name__ == '__main__':
    root = newNode(10)
    root.left = newNode(12)
    root.right = newNode(15)
    root.left.left = newNode(25)
    root.left.right = newNode(30)
    root.right.left = newNode(36)
  
    head = bTreeToCList(root)
    displayCList(head)
  
# This code is contributed by PranchalK
 
 

C#




// C# Program to convert a Binary Tree
// to a Circular Doubly Linked List
using System;
  
// Node class represents a Node of a Tree
public class Node {
    public int val;
    public Node left, right;
  
    public Node(int val)
    {
        this.val = val;
        left = right = null;
    }
}
  
// A class to represent a tree
public class Tree {
    internal Node root;
    public Tree() { root = null; }
  
    // concatenate both the lists
    // and returns the head of the List
    public virtual Node concatenate(Node leftList,
                                    Node rightList)
    {
        // If either of the list is empty,
        // then return the other list
        if (leftList == null) {
            return rightList;
        }
        if (rightList == null) {
            return leftList;
        }
  
        // Store the last Node of left List
        Node leftLast = leftList.left;
  
        // Store the last Node of right List
        Node rightLast = rightList.left;
  
        // Connect the last node of Left List
        // with the first Node of the right List
        leftLast.right = rightList;
        rightList.left = leftLast;
  
        // left of first node refers to
        // the last node in the list
        leftList.left = rightLast;
  
        // Right of last node refers to
        // the first node of the List
        rightLast.right = leftList;
  
        // Return the Head of the List
        return leftList;
    }
  
    // Method converts a tree to a circular
    // Link List and then returns the head
    // of the Link List
    public virtual Node bTreeToCList(Node root)
    {
        if (root == null) {
            return null;
        }
  
        // Recursively convert left
        // and right subtrees
        Node left = bTreeToCList(root.left);
        Node right = bTreeToCList(root.right);
  
        // Make a circular linked list of single
        // node (or root). To do so, make the
        // right and left pointers of this node
        // point to itself
        root.left = root.right = root;
  
        // Step 1 (concatenate the left list with
        //          the list with single node,
        //        i.e., current node)
        // Step 2 (concatenate the returned list
        //           with the right List)
        return concatenate(concatenate(left, root), right);
    }
  
    // Display Circular Link List
    public virtual void display(Node head)
    {
        Console.WriteLine("Circular Linked List is :");
        Node itr = head;
        do {
            Console.Write(itr.val + " ");
            itr = itr.right;
        } while (itr != head);
        Console.WriteLine();
    }
}
  
// Driver Code
public class GFG {
    public static void Main(string[] args)
    {
        // Build the tree
        Tree tree = new Tree();
        tree.root = new Node(10);
        tree.root.left = new Node(12);
        tree.root.right = new Node(15);
        tree.root.left.left = new Node(25);
        tree.root.left.right = new Node(30);
        tree.root.right.left = new Node(36);
  
        // head refers to the head of the Link List
        Node head = tree.bTreeToCList(tree.root);
  
        // Display the Circular LinkedList
        tree.display(head);
    }
}
  
// This code is contributed by Shrikant13
 
 

Javascript




<script>
// javascript Program to convert a Binary Tree to a
// Circular Doubly Linked List
  
// Node class represents a Node of a Tree
class Node {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
  
// A class to represent a 
  
        var root = null;
  
  
    // concatenate both the lists and returns the head
    // of the List
     function concatenate(leftList,  rightList) {
        // If either of the list is empty, then
        // return the other list
        if (leftList == null)
            return rightList;
        if (rightList == null)
            return leftList;
  
        // Store the last Node of left List
        var leftLast = leftList.left;
  
        // Store the last Node of right List
        var rightLast = rightList.left;
  
        // Connect the last node of Left List
        // with the first Node of the right List
        leftLast.right = rightList;
        rightList.left = leftLast;
  
        // left of first node refers to
        // the last node in the list
        leftList.left = rightLast;
  
        // Right of last node refers to the first
        // node of the List
        rightLast.right = leftList;
  
        // Return the Head of the List
        return leftList;
    }
  
    // Method converts a  to a circular
    // Link List and then returns the head
    // of the Link List
     function bTreeToCList(root) {
        if (root == null)
            return null;
  
        // Recursively convert left and right subtrees
        var left = bTreeToCList(root.left);
        var right = bTreeToCList(root.right);
  
        // Make a circular linked list of single node
        // (or root). To do so, make the right and
        // left pointers of this node point to itself
        root.left = root.right = root;
  
        // Step 1 (concatenate the left list with the list
        // with single node, i.e., current node)
        // Step 2 (concatenate the returned list with the
        // right List)
        return concatenate(concatenate(left, root), right);
    }
  
    // Display Circular Link List
     function display(head) {
        document.write("Circular Linked List is :<br/>");
        var itr = head;
        do {
            document.write(itr.val + " ");
            itr = itr.right;
        } while (itr != head);
        document.write();
    }
  
  
       // Driver Code
  
      
        // Build the 
        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);
  
        // head refers to the head of the Link List
        var head = bTreeToCList(root);
  
        // Display the Circular LinkedList
        display(head);
  
// This code contributed by umadevi9616
</script>
 
 
Output
Circular Linked List is :  25 12 30 10 36 15 

Time Complexity: O(N), As every node is visited at most once.
Auxiliary space: O(log N), The extra space is used in the recursion call stack which can grow up to a maximum size of logN as it is a binary tree.

Convert a Binary Tree to a Circular Doubly Link List by Inorder Traversal:

The idea is to do in-order traversal of the binary tree. While doing inorder traversal, keep track of the previously visited node in a variable, say prev. For every visited node, make it the next of the prev and set previous of this node as prev.

Follow the steps below to solve the problem:

  • First convert the binary tree into doubly linked list refer to this post Convert a given Binary Tree to Doubly Linked List.
  • Now convert this Doubly Linked List to circular Doubly linked list by connecting first and last node.

Below is the implementation of the above approach.

C++




// A C++ program for in-place conversion of Binary Tree to
// CDLL
#include <iostream>
using namespace std;
  
/* A binary tree node has - data , left and right pointers
 */
struct Node {
    int data;
    Node* left;
    Node* right;
};
// A utility function that converts given binary tree to
// a doubly linked list
// root --> the root of the binary tree
// head --> head of the created doubly linked list
Node* BTree2DoublyLinkedList(Node* root, Node** head)
{
    // Base case
    if (root == NULL)
        return root;
  
    // Initialize previously visited node as NULL. This is
    // static so that the same value is accessible in all
    // recursive calls
    static Node* prev = NULL;
  
    // Recursively convert left subtree
    BTree2DoublyLinkedList(root->left, head);
  
    // Now convert this node
    if (prev == NULL)
        *head = root;
    else {
        root->left = prev;
        prev->right = root;
    }
    prev = root;
  
    // Finally convert right subtree
    BTree2DoublyLinkedList(root->right, head);
    return prev;
}
// A simple recursive function to convert a given Binary
// tree to Circular Doubly Linked List using a utility
// function root --> Root of Binary Tree tail --> Pointer to
// tail node of created circular doubly linked list
Node* BTree2CircularDoublyLinkedList(Node* root)
{
    Node* head = NULL;
    Node* tail = BTree2DoublyLinkedList(root, &head);
    // make the changes to convert a DLL to CDLL
    tail->right = head;
    head->left = tail;
    // return the head of the created CDLL
    return head;
}
  
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
Node* newNode(int data)
{
    Node* new_node = new Node;
    new_node->data = data;
    new_node->left = new_node->right = NULL;
    return (new_node);
}
  
/* Function to print nodes in a given circular doubly linked
 * list */
void printList(Node* head)
{
    if (head == NULL)
        return;
    Node* ptr = head;
    do {
        cout << ptr->data << " ";
        ptr = ptr->right;
    } while (ptr != head);
}
  
/* Driver program to test above functions*/
int main()
{
    // Let us create the tree shown in above diagram
    Node* root = newNode(10);
    root->left = newNode(12);
    root->right = newNode(15);
    root->left->left = newNode(25);
    root->left->right = newNode(30);
    root->right->left = newNode(36);
  
    // Convert to DLL
    Node* head = BTree2CircularDoublyLinkedList(root);
  
    // Print the converted list
    printList(head);
  
    return 0;
}
  
// This code was contributed by Abhijeet
// Kumar(abhijeet19403)
 
 

Java




// A Java program for in-place conversion of Binary Tree to
// CDLL
  
// A binary tree node has - data, left pointer and right
// pointer
class Node {
    int data;
    Node left, right;
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
}
  
class BinaryTree {
    Node root;
    // head --> Pointer to head node of created doubly
    // linked list
    Node head;
  
    // Initialize previously visited node as NULL. This is
    // static so that the same value is accessible in all
    // recursive calls
    static Node prev = null;
  
    // A simple utility recursive function to convert a
    // given Binary tree to Doubly Linked List root --> Root
    // of Binary Tree
    void BTree2DoublyLinkedList(Node root)
    {
        // Base case
        if (root == null)
            return;
  
        // Recursively convert left subtree
        BTree2DoublyLinkedList(root.left);
  
        // Now convert this node
        if (prev == null)
            head = root;
        else {
            root.left = prev;
            prev.right = root;
        }
        prev = root;
  
        // Finally convert right subtree
        BTree2DoublyLinkedList(root.right);
    }
    // A simple function to convert a given binary tree to
    // Circular doubly linked list
    // using a utility function
    void BTree2CircularDoublyLinkedList(Node root)
    {
        BTree2DoublyLinkedList(root);
        // make the changes to convert a DLL to CDLL
        prev.right = head;
        head.left = prev;
    }
  
    /* Function to print nodes in a given doubly linked list
     */
    void printList(Node node)
    {
        if (node == null)
            return;
        Node curr = node;
        do {
            System.out.print(curr.data + " ");
            curr = curr.right;
        } while (curr != node);
    }
  
    // Driver program to test above functions
    public static void main(String[] args)
    {
        // Let us create the tree as shown in above diagram
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(10);
        tree.root.left = new Node(12);
        tree.root.right = new Node(15);
        tree.root.left.left = new Node(25);
        tree.root.left.right = new Node(30);
        tree.root.right.left = new Node(36);
  
        // convert to DLL
        tree.BTree2CircularDoublyLinkedList(tree.root);
  
        // Print the converted List
        tree.printList(tree.head);
    }
}
// This code has been contributed by Abhijeet
// Kumar(abhijeet19403)
 
 

Python




# A python program for in-place conversion of Binary Tree to DLL
# A binary tree node has data, left pointers and right pointers
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None
  
# head --> Pointer to head node of created doubly linked list
head = None
  
# Initialize previously visited node as NULL. This is
# so that the same value is accessible in all recursive
# calls
prev = None
  
# A simple recursive function to convert a given Binary tree
# to Doubly Linked List
# root --> Root of Binary Tree
def BinaryTree2DoubleLinkedList(root):
  
    # Base case
    if (root == None):
        return
  
    # Recursively convert left subtree
    BinaryTree2DoubleLinkedList(root.left)
  
    # Now convert this node
    global prev, head
    if (prev == None):
        head = root
    else:
        root.left = prev
        prev.right = root
    prev = root
  
    # Finally convert right subtree
    BinaryTree2DoubleLinkedList(root.right)
  
# Function to print nodes in a given doubly linked list
  
  
def printList(node):
    while (node != None):
        print(node.data)
        node = node.right
  
  
# Driver program to test above functions
# Let us create the tree as shown in above diagram
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)
  
# convert to DLL
BinaryTree2DoubleLinkedList(root)
  
# Print the converted List
printList(head)
  
# This code is contributed by adityamaharshi21.
 
 

C#




// A C# program for in-place conversion of Binary Tree to
// CDLL
  
using System;
  
public class Node {
    public int data;
    public Node left, right;
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
}
  
public class BinaryTree {
  
    Node root;
    // head --> Pointer to head node of created doubly
    // linked list
    Node head;
  
    // Initialize previously visited node as NULL. This is
    // static so that the same value is accessible in all
    // recursive calls
    static Node prev = null;
  
    // A simple utility recursive function to convert a
    // given Binary tree to Doubly Linked List root --> Root
    // of Binary Tree
    void BTree2DoublyLinkedList(Node root)
    {
        // Base case
        if (root == null)
            return;
  
        // Recursively convert left subtree
        BTree2DoublyLinkedList(root.left);
  
        // Now convert this node
        if (prev == null)
            head = root;
        else {
            root.left = prev;
            prev.right = root;
        }
        prev = root;
  
        // Finally convert right subtree
        BTree2DoublyLinkedList(root.right);
    }
    // A simple function to convert a given binary tree to
    // Circular doubly linked list
    // using a utility function
    void BTree2CircularDoublyLinkedList(Node root)
    {
        BTree2DoublyLinkedList(root);
        // make the changes to convert a DLL to CDLL
        prev.right = head;
        head.left = prev;
    }
  
    /* Function to print nodes in a given doubly linked list
     */
    void printList(Node node)
    {
        if (node == null)
            return;
        Node curr = node;
        do {
            Console.Write(curr.data + " ");
            curr = curr.right;
        } while (curr != node);
    }
  
    static public void Main()
    {
  
        // Let us create the tree as shown in above diagram
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(10);
        tree.root.left = new Node(12);
        tree.root.right = new Node(15);
        tree.root.left.left = new Node(25);
        tree.root.left.right = new Node(30);
        tree.root.right.left = new Node(36);
  
        // convert to DLL
        tree.BTree2CircularDoublyLinkedList(tree.root);
  
        // Print the converted List
        tree.printList(tree.head);
    }
}
  
// This code is contributed by lokesh(lokeshmvs21).
 
 

Javascript




// A javascript program for in-place conversion of Binary Tree to DLL
// A binary tree node has data, left pointers and right pointers
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}
var root;
  
// head --> Pointer to head node of created doubly linked list
var head;
  
// Initialize previously visited node as NULL. This is
// so that the same value is accessible in all recursive
// calls
var prev = null;
  
// A simple recursive function to convert a given Binary tree
// to Doubly Linked List
// root --> Root of Binary Tree
function BinaryTree2DoubleLinkedList(root)
{
  
    // Base case
    if (root == null)
        return;
          
    // Recursively convert left subtree
    BinaryTree2DoubleLinkedList(root.left);
      
    // Now convert this node
    if (prev == null)
        head = root;
    else {
        root.left = prev;
        prev.right = root;
    }
    prev = root;
      
    // Finally convert right subtree
    BinaryTree2DoubleLinkedList(root.right);
}
  
/* Function to print nodes in a given doubly linked list */
function printList(node) {
    while (node != null) {
        console.log(node.data + " ");
        node = node.right;
    }
}
  
// Driver program to test above functions
// Let us create the tree as shown in above diagram
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);
  
// convert to DLL
BinaryTree2DoubleLinkedList(root);
  
// Print the converted List
printList(head);
  
// This code is contributed by ishankhandelwals.
 
 
Output
25 12 30 10 36 15 

Time Complexity: O(N), As every node is visited at most once.
Auxiliary space: O(log N), The extra space is used in the recursive function call stack which can grow upto a maximum size of logN.

This approach was contributed by Abhijeet Kumar



Next Article
Convert Ternary Expression to a Binary Tree

C

Chirag Agarwal
Improve
Article Tags :
  • DSA
  • Linked List
  • Tree
  • Binary Tree
Practice Tags :
  • Linked List
  • Tree

Similar Reads

  • Binary Tree Data Structure
    A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
    3 min read
  • Introduction to Binary Tree
    Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Representation of Binary TreeEach node in a Binar
    15+ min read
  • Properties of Binary Tree
    This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levels Note: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A binary tree can have at most
    4 min read
  • Applications, Advantages and Disadvantages of Binary Tree
    A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web
    2 min read
  • Binary Tree (Array implementation)
    Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
    6 min read
  • Maximum Depth of Binary Tree
    Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node. Examples: Input: Output: 2Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which h
    11 min read
  • Insertion in a Binary Tree in level order
    Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner. Examples: Input: key = 12 Output: Explanation: Node with value 12 is inserted into the binary tree at the first position available in level order manner. Approach:
    8 min read
  • Deletion in a Binary Tree
    Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
    12 min read
  • Enumeration of Binary Trees
    A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar
    3 min read
  • Types of Binary Tree

    • Types of Binary Tree
      We have discussed Introduction to Binary Tree in set 1 and the Properties of Binary Tree in Set 2. In this post, common types of Binary Trees are discussed. Types of Binary Tree based on the number of children:Following are the types of Binary Tree based on the number of children: Full Binary TreeDe
      7 min read

    • Complete Binary Tree
      We know a tree is a non-linear data structure. It has no limitation on the number of children. A binary tree has a limitation as any node of the tree has at most two children: a left and a right child. What is a Complete Binary Tree?A complete binary tree is a special type of binary tree where all t
      7 min read

    • Perfect Binary Tree
      What is a Perfect Binary Tree? A perfect binary tree is a special type of binary tree in which all the leaf nodes are at the same depth, and all non-leaf nodes have two children. In simple terms, this means that all leaf nodes are at the maximum depth of the tree, and the tree is completely filled w
      4 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