-
Notifications
You must be signed in to change notification settings - Fork 0
/
floorInBST
45 lines (39 loc) · 925 Bytes
/
floorInBST
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
#include <bits/stdc++.h>
/************************************************************
Following is the TreeNode class structure
template <typename T>
class TreeNode {
public:
T val;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T val) {
this->val = val;
left = NULL;
right = NULL;
}
};
************************************************************/
int solve(TreeNode<int> * root, int X , int* mx)
{
if(root == NULL){
return -1;
}
if(root->val > X){
return solve(root->left , X , mx);
}
else if(root->val < X){
*mx = max(*mx , root->val);
return solve(root->right ,X , mx);
}
else{
*mx = max(*mx , root->val);
return *mx;
}
}
int floorInBST(TreeNode<int> * root, int X)
{
int ans = -1;
solve(root , X , &ans);
return ans;
}