700548. Binary Tree to CDLL
Binary Tree to CDLL
Slug: binary-tree-to-cdll
Difficulty: Medium
Id: 700548
Topic Tags: Linked List, Tree, Data Structures
Company Tags: Amazon, SAP Labs
Summary
Given a binary tree, the task is to convert it into a circular doubly linked list (CDLL). The CDLL should have the same order of nodes as the original binary tree. This problem involves manipulating the tree structure and creating a new linked list.
Detailed Explanation
To solve this problem, we'll first traverse the binary tree in pre-order manner. Then, we'll create a new node for each visited node and link it to the previous node to form a CDLL. The circular part of the CDLL is handled by linking the last node to the first node.
Here's a step-by-step breakdown of the solution:
- Initialize two pointers,
prevandcurr, toNULL. - Traverse the binary tree in pre-order manner (root -> left -> right).
- For each visited node:
- Create a new node with the same value as the original node.
- If this is not the first node, link the new node to the previous node (
prev). - Update
prevandcurrpointers.
- Link the last node to the first node to form a circular doubly linked list.
Time Complexity
The time complexity of this solution is O(n), where n is the number of nodes in the binary tree, as we visit each node once.
Space Complexity
The space complexity of this solution is O(n) as well, due to the creation of new nodes and their linking into a CDLL.
Optimized Solutions
Java
class Node {
int val;
Node left, right;
public Node(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
public class BinaryTreeToCDLL {
public static void binaryTreeToCDLL(Node root) {
if (root == null)
return;
Node prev = null, curr = root;
while (curr != null) {
// Create a new node with the same value as the original node
Node newNode = new Node(curr.val);
if (prev != null) {
// Link the new node to the previous node
newNode.right = prev;
prev.left = newNode;
}
curr = curr.right; // Move to the right child
prev = newNode; // Update the previous node
}
// Link the last node to the first node to form a circular doubly linked list
prev.right = root;
root.left = prev;
}
}