// Author :: Gaurav Ahirwar
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node* left, *right;
};
typedef struct node* Node;
typedef struct node node;
void inorder(Node root) {
if(!root) return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
Node newNode(int data)
{
Node temp = (Node)malloc(sizeof(struct node));
temp->data = data;
temp->left = temp->right = NULL;
return(temp);
}
void printlist(Node head) {
if(!head) {
cout << "Empty List\n";
return;
}
while(head != NULL) {
cout << head->data << " ";
// if(head->next) cout << "-> ";
head = head->right;
}
cout << endl;
}
/*function of convert binary tree to DLL */
void doubly(node *root, node **prev, node **head) {
if(!root) return;
doubly(root->left, prev, head);
if(!(*prev)) *head = root;/* if prev null set head */
root->left = *prev; /*update left pointer */
*prev = root; /*Update prev for next call*/
doubly(root->right, prev, head);
}
/*Wrapper for converting binary tree to DLL*/
void convert(node **root) {
Node prev = NULL;
Node head;
doubly(*root, &prev, &head);
/*update right pointers of all node in the list*/
while(prev->left) {
prev->left->right = prev;
prev = prev->left;
}
*root = head; /* update root as head of DLL */
}
/*function to print two sorted DLL in combined sorted form*/
void printmerged(Node root1, Node root2) {
while(root1 && root2) {
if(root1->data < root2->data) {
cout << root1->data << " ";
root1 = root1->right;
}
else {
cout << root2->data << " ";
root2 = root2->right;
}
}
while(root1) {
cout << root1->data << " ";
root1 = root1->right;
}
while(root2) {
cout << root2->data << " ";
root2 = root2->right;
}
cout << endl;
}
int main() {
// Let us construct the BST shown in the above figure
node *root2 = newNode(4);
root2->left = newNode(2);
root2->right = newNode(6);
root2->left->left = newNode(1);
root2->left->right = newNode(3);
root2->right->left = newNode(5);
root2->right->right = newNode(7);
/* Constructed binary tree is
4
/ \
2 6
/ \ / \
1 3 5 7
*/
node *root1 = newNode(100);
root1->left = newNode(90);
root1->right = newNode(105);
root1->left->left = newNode(70);
root1->left->right = newNode(95);
root1->right->left = newNode(103);
root1->right->right = newNode(106);
/* Constructed binary tree is
100
/ \
90 105
/ \ / \
70 95 103 106
*/
convert(&root1);
convert(&root2);
printmerged(root1, root2);
return 0;
}