#include <stdio.h>
#include <stdlib.h>
// BST node structure
typedef struct Node {
int val;
struct Node* left;
struct Node* right;
struct Node* parent;
} Node;
// Create new node
Node* newNode(int val, Node* parent) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = val;
node->left = NULL;
node->right = NULL;
node->parent = parent;
return node;
}
// Insert node in BST with parent pointer
Node* insert(Node* root, int val, Node* parent) {
if (root == NULL) return newNode(val, parent);
if (val < root->val) root->left = insert(root->left, val, root);
else root->right = insert(root->right, val, root);
return root;
}
// Find leftmost node in subtree
Node* leftmost(Node* node) {
while (node && node->left != NULL) {
node = node->left; // move left to find smallest
}
return node;
}
// Find inorder successor of given node
Node* inorderSuccessor(Node* node) {
if (node == NULL) return NULL;
// Case 1: right child exists
if (node->right != NULL) {
return leftmost(node->right); // successor is leftmost in right subtree
}
// Case 2: no right child, go up to parent
Node* p = node->parent;
while (p != NULL && node == p->right) {
node = p; // move up
p = p->parent;
}
return p; // first parent where node is in left subtree
}
// Find node with given value
Node* findNode(Node* root, int val) {
if (root == NULL) return NULL;
if (val == root->val) return root;
if (val < root->val) return findNode(root->left, val);
else return findNode(root->right, val);
}
// Print result
void printSuccessor(Node* root, int val) {
Node* node = findNode(root, val);
if (node == NULL) {
printf("Node %d not found\n", val);
return;
}
Node* succ = inorderSuccessor(node);
if (succ != NULL) {
printf("Inorder Successor of %d is %d\n", val, succ->val);
} else {
printf("Inorder Successor of %d does not exist\n", val);
}
}
int main() {
Node* root = NULL;
root = insert(root, 20, NULL);
root = insert(root, 10, NULL);
root = insert(root, 30, NULL);
root = insert(root, 15, NULL);
root = insert(root, 40, NULL);
printSuccessor(root, 15);
return 0;
}
if (node->right != NULL) { return leftmost(node->right); }
If right child exists, successor is leftmost node in right subtree
while (p != NULL && node == p->right) { node = p; p = p->parent; }
Move up to find first ancestor where node is in left subtree
Return that ancestor as successor or NULL if none
Inorder Successor of 15 is 20