-
Notifications
You must be signed in to change notification settings - Fork 8
/
in-place-convert-a-given-binary-tree-to-doubly-linked-list.cpp
72 lines (64 loc) · 1.4 KB
/
in-place-convert-a-given-binary-tree-to-doubly-linked-list.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
// https://www.geeksforgeeks.org/in-place-convert-a-given-binary-tree-to-doubly-linked-list/
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *left;
Node *right;
};
Node * getnewnode(int data){
Node *newnode = new Node();
newnode->data = data;
newnode->left = NULL;
newnode->right = NULL;
}
Node *convertToDLL(Node *root){
if(!root)
return root;
if(root->left){
Node *l = convertToDLL(root->left);
for(;l->right;l=l->right);
root->left = l;
l->right = root;
}
if(root->right){
Node *r = convertToDLL(root->right);
for(;r->left;r=r->left);
r->left = root;
root->right = r;
}
return root;
}
void btoDLL(Node *root, Node **head){
if(!root) return;
btoDLL(root->right, head);
root->right = *head;
if(*head)
(*head)->left = root;
*head = root;
btoDLL(root->left, head);
}
int main(){
Node * root = getnewnode(10);
root->left = getnewnode(12);
root->right = getnewnode(15);
root->left->left = getnewnode(25);
root->left->right = getnewnode(30);
root->right->left = getnewnode(36);
Node *res = convertToDLL(root);
while(res->left)
res = res->left;
while(res){
cout << res->data << " ";
res = res->right;
}
cout << endl;
Node *head = NULL;
btoDLL(root, &head);
Node *temp = head;
while(temp){
cout << temp->data << " ";
temp = temp->right;
}
return 0;
}