File tree Expand file tree Collapse file tree 1 file changed +107
-0
lines changed
Expand file tree Collapse file tree 1 file changed +107
-0
lines changed Original file line number Diff line number Diff line change 1+ {
2+ #include < bits/stdc++.h>
3+ using namespace std ;
4+ struct Node {
5+ int data;
6+ Node *left,*right;
7+
8+ Node (int x){
9+ data = x;
10+ left = NULL ;
11+ right = NULL ;
12+ }
13+ };
14+ void insert (Node *root, int a1,int a2, char lr){
15+ if (root==NULL )
16+ return ;
17+ if (root->data ==a1){
18+ switch (lr){
19+ case ' L' :root->left =new Node (a2);
20+ break ;
21+ case ' R' :root->right =new Node (a2);
22+ break ;
23+ }
24+ }
25+ else {
26+ insert (root->left , a1, a2, lr);
27+ insert (root->right , a1, a2, lr);
28+ }
29+ }
30+ Node *convertToDLL (Node *root,Node **head_ref);
31+ int main (){
32+ int t;
33+ cin>>t;
34+ while (t--){
35+ int n;
36+ cin>>n;
37+ Node *root=NULL ;
38+ while (n--){
39+ int a1,a2;
40+ char lr;
41+ cin>>a1>>a2;
42+ scanf (" %c" ,&lr);
43+ if (root==NULL ){
44+ root=new Node (a1);
45+ switch (lr){
46+ case ' L' :root->left =new Node (a2);
47+ break ;
48+ case ' R' :root->right =new Node (a2);
49+ break ;
50+ }
51+ }
52+ else {
53+ insert (root,a1,a2,lr);
54+ }
55+ }
56+
57+ Node *head=NULL ;
58+ root=convertToDLL (root,&head);
59+
60+ while (head->right !=NULL ){
61+ cout<<head->data <<" " ;
62+ head=head->right ;
63+ }
64+
65+ cout<<head->data <<endl;
66+ while (head!=NULL ){
67+ cout<<head->data <<" " ;
68+ head = head->left ;
69+ }
70+ cout<<endl;
71+ }
72+ }
73+
74+ }
75+ /* This is a function problem.You only need to complete the function given below*/
76+ /* Complete the function below
77+ Node is as follows:
78+ struct Node{
79+ int data;
80+ Node *left,*right;
81+
82+ Node(int x){
83+ data = x;
84+ left = NULL;
85+ right = NULL;
86+ }
87+ };
88+ */
89+ Node *convertToDLL (Node *root,Node **head_ref)
90+ {
91+ // add code here.
92+
93+ static Node* prev = NULL ;
94+ if (!root) return NULL ;
95+ convertToDLL (root->left , head_ref);
96+
97+ if (!root->left && !root->right ){ // if its a leaf node
98+ if (!(*head_ref))
99+ *head_ref = root;
100+ else {
101+ root->left = prev;
102+ prev->right = root;
103+ }
104+ prev = root;
105+ }
106+ convertToDLL (root->right , head_ref);
107+ }
You can’t perform that action at this time.
0 commit comments