VOOZH about

URL: https://www.geeksforgeeks.org/dsa/potd-solutions-17-nov-23-binary-tree-to-cdll/

⇱ POTD Solutions | 17 Nov' 23 | Binary Tree to CDLL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

POTD Solutions | 17 Nov' 23 | Binary Tree to CDLL

Last Updated : 23 Jul, 2025

View all POTD Solutions

Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Tree but will also help you build up problem-solving skills.

👁 17th-nov
POTD Solution 17 November 2023
We recommend you to try this problem on our GeeksforGeeks Practice portal first, and maintain your streak to earn Geeksbits and other exciting prizes, before moving towards the solution.

Given a Binary Tree of N edges. The task is to convert this to a Circular Doubly Linked List (CDLL) in-place. The left and right pointers in nodes are to be used as previous and next pointers respectively in CDLL. The order of nodes in CDLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the CDLL.

Examples:

Input:👁 binaryTreeToLL

Output:
3 1 2 
2 1 3
Explanation: After converting tree to CDLL when CDLL is is traversed from head to tail and then tail to head, elements are displayed as in the output.

Input:

👁 binaryTreeToLL-(1)
Output:
40 20 60 10 30 
30 10 60 20 40

Explanation: After converting tree to CDLL, when CDLL is is traversed from head to tail and then tail to head, elements are displayed as in the output.

The idea is to use Recursion and 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.

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:

Time Complexity: O(N), where N is the number of nodes in the binary tree
Auxiliary Space: O(h), h is the height of the binary tree

Comment
Article Tags: