CODE:
#include <iostream>
using namespace std;
// Node definition
struct Node {
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
// Insertion in BST
Node* insert(Node* root, int val) {
if (root == nullptr) {
return new Node(val);
}
if (val < root->data) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
// Finding inorder successor
Node* findInorderSuccessor(Node* root, Node* target) {
if (target->right != nullptr) {
Node* current = target->right;
while (current->left != nullptr) {
current = current->left;
}
return current;
} else {
Node* successor = nullptr;
Node* ancestor = root;
while (ancestor != target) {
if (target->data < ancestor->data) {
successor = ancestor;
ancestor = ancestor->left;
} else {
ancestor = ancestor->right;
}
}
return successor;
}
}
// Finding inorder predecessor
Node* findInorderPredecessor(Node* root, Node* target) {
if (target->left != nullptr) {
Node* current = target->left;
while (current->right != nullptr) {
current = current->right;
}
return current;
} else {
Node* predecessor = nullptr;
Node* ancestor = root;
while (ancestor != target) {
if (target->data > ancestor->data) {
predecessor = ancestor;
ancestor = ancestor->right;
} else {
ancestor = ancestor->left;
}
}
return predecessor;
}
}
// Inorder traversal
void inorderTraversal(Node* root) {
if (root == nullptr) {
return;
}
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
int main() {
// Creating BST
Node* root = nullptr;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
cout << "Inorder traversal of the BST: ";
inorderTraversal(root);
cout << endl;
Node* target = root->right->right; // Assuming target node is 80
// Finding inorder successor
Node* successor = findInorderSuccessor(root, target);
if (successor != nullptr) {
cout << "Inorder successor of " << target->data << " is " << successor->data << endl;
} else {
cout << "No inorder successor found for " << target->data << endl;
}
// Finding inorder predecessor
Node* predecessor = findInorderPredecessor(root, target);
if (predecessor != nullptr) {
cout << "Inorder predecessor of " << target->data << " is " << predecessor->data << endl;
} else {
cout << "No inorder predecessor found for " << target->data << endl;
}
return 0;
}