-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathleaves_to_dll.cpp
107 lines (99 loc) · 1.79 KB
/
leaves_to_dll.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
{
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *left,*right;
Node(int x){
data = x;
left = NULL;
right = NULL;
}
};
void insert(Node *root, int a1,int a2, char lr){
if(root==NULL)
return;
if(root->data==a1){
switch(lr){
case 'L':root->left=new Node(a2);
break;
case 'R':root->right=new Node(a2);
break;
}
}
else{
insert(root->left, a1, a2, lr);
insert(root->right, a1, a2, lr);
}
}
Node *convertToDLL(Node *root,Node **head_ref);
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
Node *root=NULL;
while(n--){
int a1,a2;
char lr;
cin>>a1>>a2;
scanf(" %c",&lr);
if(root==NULL){
root=new Node(a1);
switch(lr){
case 'L':root->left=new Node(a2);
break;
case 'R':root->right=new Node(a2);
break;
}
}
else{
insert(root,a1,a2,lr);
}
}
Node *head=NULL;
root=convertToDLL(root,&head);
while(head->right!=NULL){
cout<<head->data<<" ";
head=head->right;
}
cout<<head->data<<endl;
while(head!=NULL){
cout<<head->data<<" ";
head = head->left;
}
cout<<endl;
}
}
}
/*This is a function problem.You only need to complete the function given below*/
/*Complete the function below
Node is as follows:
struct Node{
int data;
Node *left,*right;
Node(int x){
data = x;
left = NULL;
right = NULL;
}
};
*/
Node *convertToDLL(Node *root,Node **head_ref)
{
//add code here.
static Node* prev = NULL;
if(!root) return NULL;
convertToDLL(root->left, head_ref);
if(!root->left && !root->right){ // if its a leaf node
if(!(*head_ref))
*head_ref = root;
else{
root->left = prev;
prev->right = root;
}
prev = root;
}
convertToDLL(root->right, head_ref);
}