#include<stdio.h>
#include<stdlib.h>
struct
Node{
int
key;
struct
Node *left;
struct
Node *right;
struct
Node *parent;
};
struct
Node* insert(
int
key,
struct
Node *root,
struct
Node *parent)
{
if
(!root)
{
struct
Node *node = (
struct
Node*)
malloc
(
sizeof
(
struct
Node));
if
(node)
{
node->key = key;
node->left = node->right = NULL;
node->parent = parent;
return
node;
}
else
printf
(
"Could not allocate memory."
);
}
else
if
(key == root->key)
printf
(
"Duplicates are not allowed in BST."
);
else
if
(key > root->key)
root->right = insert(key, root->right,root);
else
root->left = insert(key, root->left, root);
return
root;
}
struct
Node* search(
int
key,
struct
Node *root)
{
if
(!root)
return
NULL;
else
if
( key == root->key)
return
root;
else
if
(key > root->key)
return
search(key, root->right);
else
return
search(key, root->left);
}
struct
Node* preOrderSuccessor(
int
key,
struct
Node *root){
struct
Node *node = search(key, root);
if
(!node){
printf
(
"%d do not exists in BST.\n"
, key);
return
NULL;
}
if
(node->left)
return
node->left;
else
if
(node->right)
return
node->right;
else
{
struct
Node *temp = node->parent;
while
(temp){
if
(key < temp->key && temp->right)
break
;
temp = temp->parent;
}
return
temp ? temp->right : NULL;
}
}
void
preOrder(
struct
Node *root)
{
if
(root)
{
printf
(
"%d "
, root->key);
preOrder(root->left);
preOrder(root->right);
}
}
int
main()
{
struct
Node *ROOT = NULL;
int
a[] = {51, 39, 31, 54, 92, 42, 21, 10,
26, 52, 36, 47, 82, 5, 62};
int
n =
sizeof
(a) /
sizeof
(a[0]);
for
(
int
i = 0 ; i < n; i++)
{
printf
(
"Inserting %2d....."
, a[i]);
ROOT = insert(a[i], ROOT, NULL);
printf
(
"Finished Insertion.\n"
);
}
printf
(
"\nPre-Order Traversal : "
);
preOrder(ROOT);
printf
(
"\n====================================="
);
printf
(
"\n%-10s%s\n"
,
"Key"
,
"Pre-Order Successor"
);
printf
(
"=====================================\n"
);
struct
Node *successor = NULL;
for
(
int
i = 0 ; i < n; ++i)
{
successor = preOrderSuccessor(a[i], ROOT);
if
(successor)
printf
(
"%-10d%d\n"
, a[i], successor->key);
else
printf
(
"%-10dDo Not Exist.\n"
, a[i]);
}
return
0;
}