forked from striver79/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflattenLLCpp
40 lines (31 loc) · 868 Bytes
/
flattenLLCpp
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
Node* mergeTwoLists(Node* a, Node* b) {
Node *temp = new Node(0);
Node *res = temp;
while(a != NULL && b != NULL) {
if(a->data < b->data) {
temp->bottom = a;
temp = temp->bottom;
a = a->bottom;
}
else {
temp->bottom = b;
temp = temp->bottom;
b = b->bottom;
}
}
if(a) temp->bottom = a;
else temp->bottom = b;
return res -> bottom;
}
Node *flatten(Node *root)
{
if (root == NULL || root->next == NULL)
return root;
// recur for list on right
root->next = flatten(root->next);
// now merge
root = mergeTwoLists(root, root->next);
// return the root
// it will be in turn merged with its left
return root;
}