#include <stdio.h>
#include <stdlib.h>
// Define BST node
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// Create new node
Node* newNode(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// Insert node in BST
Node* insert(Node* root, int data) {
if (root == NULL) return newNode(data);
if (data < root->data) root->left = insert(root->left, data);
else root->right = insert(root->right, data);
return root;
}
// Find inorder predecessor
Node* inorderPredecessor(Node* root, int key) {
Node* curr = root;
Node* predecessor = NULL;
// First find the node with key
while (curr != NULL && curr->data != key) {
if (key < curr->data) curr = curr->left;
else curr = curr->right;
}
if (curr == NULL) return NULL; // key not found
// Case 1: If left subtree exists, predecessor is rightmost node in left subtree
if (curr->left != NULL) {
predecessor = curr->left;
while (predecessor->right != NULL) {
predecessor = predecessor->right; // move right to find max
}
return predecessor;
}
// Case 2: No left subtree, predecessor is ancestor where current node is in right subtree
Node* ancestor = root;
predecessor = NULL;
while (ancestor != curr) {
if (curr->data > ancestor->data) {
predecessor = ancestor; // potential predecessor
ancestor = ancestor->right;
} else {
ancestor = ancestor->left;
}
}
return predecessor;
}
// Print result
void printPredecessor(Node* root, int key) {
Node* pred = inorderPredecessor(root, key);
if (pred != NULL) printf("Inorder predecessor of %d is %d\n", key, pred->data);
else printf("No inorder predecessor for %d\n", key);
}
int main() {
Node* root = NULL;
int values[] = {20, 10, 30, 5, 15, 40};
int n = sizeof(values)/sizeof(values[0]);
for (int i = 0; i < n; i++) {
root = insert(root, values[i]);
}
printPredecessor(root, 20);
return 0;
}while (curr != NULL && curr->data != key) { if (key < curr->data) curr = curr->left; else curr = curr->right; }
Locate the node with the given key
if (curr->left != NULL) { predecessor = curr->left; while (predecessor->right != NULL) predecessor = predecessor->right; return predecessor; }
If left subtree exists, find rightmost node there as predecessor
Node* ancestor = root; predecessor = NULL; while (ancestor != curr) { if (curr->data > ancestor->data) { predecessor = ancestor; ancestor = ancestor->right; } else { ancestor = ancestor->left; } }
If no left subtree, find deepest ancestor smaller than current node
Inorder predecessor of 20 is 15