-
Notifications
You must be signed in to change notification settings - Fork 0
/
142. Predecessor And Successor In BST.cpp
74 lines (61 loc) · 1.42 KB
/
142. Predecessor And Successor In BST.cpp
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
66
67
68
69
70
71
72
73
74
#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;
}
}
};
*************************************************************/
int ip(BinaryTreeNode<int>* root, int key){
int pred = -1;
if(root == NULL)
return pred;
while(root){
if(root->data >= key){
root = root->left;
} else {
pred = root->data;
root = root->right;
}
}
return pred;
}
int is(BinaryTreeNode<int>* root, int key){
int succ = -1;
if(root == NULL)
return succ;
while(root){
if(root->data > key){
succ = root->data;
root = root->left;
}
else root = root->right;
}
return succ;
}
pair<int,int> predecessorSuccessor(BinaryTreeNode<int>* root, int key)
{
pair<int,int> ans;
ans.first = ip(root, key);
ans.second = is(root, key);
return ans;
}