-
Notifications
You must be signed in to change notification settings - Fork 5
/
BS_InorderSuccessorBST.cpp
64 lines (55 loc) · 988 Bytes
/
BS_InorderSuccessorBST.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
/*
Inorder Successor
https://binarysearch.com/problems/Inorder-Successor
*/
/**
* class Tree {
* public:
* int val;
* Tree *left;
* Tree *right;
* };
*/
/*
int T;
Tree* par;
Tree* search(Tree* root)
{
if(root->val == T)
return root;
else if(T < root->val)
{
par = root;
return search(root->left);
}
else
return search(root->right);
}
int solve(Tree* root, int t) {
T=t;
par = nullptr;
Tree* node = search(root);
if(par != nullptr && !node->right)
return par->val;
Tree* rightChild = node->right;
while(rightChild->left)
rightChild = rightChild->left;
return rightChild->val;
}
*/
int solve(Tree* root, int t) {
int ans=-1;
while(root)
{
if(t < root->val)
{
ans = root->val;
root = root->left;
}
else
{
root = root->right;
}
}
return ans;
}