// C++ solution code goes here
struct Node
{
int key;
struct Node *left;
struct Node *right;
Node(int x){
key = x;
left = NULL;
right = NULL;
}
};
*/
// This function finds predecessor and successor of key in BST.
// It sets pre and suc as predecessor and successor respectively
class Solution
{
public:
void findSuccessor(Node* root, Node*& s, int key)
{
if(!root)
{
s == nullptr;
return;
}
Node* cur = root;
while(cur)
{
if(cur->key <= key)
{
cur = cur->right;
}
else
{
s = cur;
cur = cur->left;
}
}
}
void findPredecessor(Node* root, Node* &p, int key)
{
if(!root)
{
p = nullptr;
return;
}
Node* cur = root;
while(cur)
{
if(cur->key >= key)
cur = cur->left;
else
{
p = cur;
cur = cur->right;
}
}
}
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
{
// Your code goes here
findSuccessor(root, suc, key);
findPredecessor(root, pre, key);
}
};