-
Notifications
You must be signed in to change notification settings - Fork 0
/
Predecessor And Successor
65 lines (56 loc) · 1.28 KB
/
Predecessor And Successor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <bits/stdc++.h>
/*************************************************************
Following is the Binary Tree node structure
template <typename T>
class BinaryTreeNode
{
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
}
~BinaryTreeNode() {
if (left)
{
delete left;
}
if (right)
{
delete right;
}
}
};
*************************************************************/
void solve(BinaryTreeNode<int>*root,int key,int &pre,int &suc)
{
if(root==nullptr)
{
return;
}
solve(root->left,key,pre,suc);
if(root->data<key)
{
pre=root->data;
}
if(root->data>key and suc==-1)
{
suc=root->data;
}
solve(root->right,key,pre,suc);
}
pair<int,int> predecessorSuccessor(BinaryTreeNode<int>* root, int key)
{
// Write your code here.
int pre=-1;
int suc=-1;
if(root==nullptr)
{
return {-1, -1};
}
solve(root,key,pre,suc);
return {pre, suc};
}