-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree to CDLL
51 lines (43 loc) Β· 1.41 KB
/
Binary Tree to CDLL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution
{
public:
// Helper function to perform in-order traversal and connect nodes
void convertToCircularDLL(Node *root, Node *&head, Node *&tail)
{
if (!root)
return;
// Recursive in-order traversal
convertToCircularDLL(root->left, head, tail);
// Connect the current node to the circular doubly linked list
if (!head)
{
// If head is null, set head and tail to the current node
head = tail = root;
}
else
{
// Connect the current node to the right of the tail
tail->right = root;
// Connect the tail to the left of the current node
root->left = tail;
// Update the tail to the current node
tail = root;
}
// Recursive in-order traversal
convertToCircularDLL(root->right, head, tail);
}
// Function to convert binary tree into circular doubly linked list.
Node *bTreeToCList(Node *root)
{
if (!root)
return nullptr;
// Initialize head and tail pointers
Node *head = nullptr, *tail = nullptr;
// Perform in-order traversal and connect nodes
convertToCircularDLL(root, head, tail);
// Connect the head and tail of the circular doubly linked list
head->left = tail;
tail->right = head;
return head;
}
};