#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right, *next;
Node(int data) {
this->data = data;
left = NULL;
right = NULL;
next = NULL;
}
~Node() {
delete left;
delete right;
left = NULL;
right = NULL;
}
};
class Tree {
private:
Node *root;
class maxMin {
public:
Node *max;
Node *min;
maxMin() {}
maxMin(maxMin left, maxMin right, Node *root) {
this->min = left.min;
this->max = right.max;
if(this->max == NULL)
this->max = root;
if(this->min == NULL)
this->min = root;
}
};
maxMin convertBSTtoDLLUtil(Node *root) {
if(root == NULL) {
maxMin a;
a.max = NULL;
a.min = NULL;
return a;
}
maxMin left = convertBSTtoDLLUtil(root->left);
maxMin right = convertBSTtoDLLUtil(root->right);
if(left.max != NULL) {
(left.max)->right = root;
}
root->left = left.max;
if(right.min != NULL) {
(right.min)->left = root;
}
root->right = right.min;
maxMin returnVal(left, right, root);
return returnVal;
}
public:
Tree() {
// cout << "In Constructor 1\n";
root = NULL;
constructTree();
}
void convertBSTtoDLL() {
maxMin temp = this->convertBSTtoDLLUtil(this->root);
Node* tempRoot = temp.min;
while(tempRoot != NULL) {
cout << tempRoot->data << "-->";
tempRoot = tempRoot->right;
}
cout << "NULL\n";
}
void constructTree() {
/*
* BST
*/
root = new Node(100);
root->left = new Node(90);
root->right = new Node(110);
root->left->left = new Node(80);
root->left->right = new Node(91);
root->right->left = new Node(105);
root->right->right = new Node(120);
root->left->left->left = new Node(71);
root->left->left->right = new Node(80);
root->right->left->right = new Node(107);
}
~Tree() {
// cout << "In destructor\n";
delete root;
root = NULL;
}
};
int main() {
Tree t1;
t1.convertBSTtoDLL();
return 0;
}