CODE:
#include <iostream>
using namespace std;
// Node structure for the threaded binary search tree
struct Node {
int data;
Node* left;
Node* right;
bool rightThread; // Indicates if the right pointer is a thread
};
// Function to create a new node
Node* createNode(int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->left = newNode->right = nullptr;
newNode->rightThread = false;
return newNode;
}
// Function to insert a node into the threaded binary search tree
void insert(Node*& root, int data) {
Node* newNode = createNode(data);
Node* curr = root;
Node* prev = nullptr;
while (curr != nullptr) {
prev = curr;
if (data < curr->data) {
if (curr->left != nullptr)
curr = curr->left;
else
break;
} else {
if (curr->right != nullptr && !curr->rightThread)
curr = curr->right;
else
break;
}
}
if (prev == nullptr) {
root = newNode;
} else if (data < prev->data) {
newNode->right = prev;
prev->left = newNode;
} else {
newNode->right = prev->right;
prev->right = newNode;
prev->rightThread = false;
}
}
// Function to perform in-order traversal of the threaded binary search tree
void inOrderTraversal(Node* root) {
Node* curr = root;
while (curr != nullptr) {
while (curr->left != nullptr)
curr = curr->left;
cout << curr->data << " ";
if (curr->rightThread)
curr = curr->right;
else {
curr = curr->right;
if (curr != nullptr)
cout << curr->data << " ";
}
}
}
int main() {
Node* root = nullptr;
// Inserting elements into the threaded binary search tree
insert(root, 5);
insert(root, 3);
insert(root, 7);
insert(root, 2);
insert(root, 4);
insert(root, 6);
insert(root, 8);
// Performing in-order traversal
cout << "In-order traversal: ";
inOrderTraversal(root);
cout << endl;
return 0;
}