-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree to CDLL.cpp
118 lines (103 loc) · 2.45 KB
/
Binary Tree to CDLL.cpp
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*---------------THREE APPROACHES-------------*/
/*---1. Vector || T - O(N) || T - S(N+N+height of tree)----*/
class Solution
{
public:
//Function to convert binary tree into circular doubly linked list.
void inorder(Node* root,vector<int>& a)
{
if(!root)
return ;
inorder(root->left,a);
a.push_back(root->data);
inorder(root->right,a);
}
Node *bTreeToCList(Node *root)
{
vector<int> a;
inorder(root,a);
Node* head=NULL;
Node* tail=NULL;
for(auto it:a)
{
Node* newnode=newNode(it);
if(!head)
{
head=newnode;
tail=newnode;
}
else
{
newnode->left=tail;
tail->right=newnode;
tail=newnode;
}
}
head->left=tail;
tail->right=head;
return head;
}
};
/*---2. Inorder || T - O(N) || S - O(N+height of the tree)----*/
class Solution
{
public:
//Function to convert binary tree into circular doubly linked list.
void inorder(Node* root,Node* &head,Node* &tail)
{
if(!root)
return ;
inorder(root->left,head,tail);
if(head==NULL)
{
Node* newnode=newNode(root->data);
head=newnode;
tail=newnode;
}
else
{
Node* newnode=newNode(root->data);
newnode->left=tail;
tail->right=newnode;
tail=newnode;
}
inorder(root->right,head,tail);
}
Node *bTreeToCList(Node *root)
{
Node* head=NULL;
Node* tail=NULL;
inorder(root,head,tail);
head->left=tail;
tail->right=head;
return head;
}
};
/*-----------3. Inplace || T - O(N) || S - O(height of tree)------*/
class Solution
{
Node *prev = NULL;
Node *head = NULL;
void inorder(Node *root)
{
if(!root)
return;
inorder(root->left);
if(!head)
head = prev = root;
else
{
prev->right = root;
root->left = prev;
}
prev = root;
inorder(root->right);
}
public:
Node *bTreeToCList(Node *root) {
inorder(root);
head->left = prev;
prev->right = head;
return head;
}
};