#include <bits/stdc++.h>
using namespace std;
// tree node is defined
class TreeNode
{
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int data)
{
val = data;
left = NULL;
right = NULL;
}
};
void searchLargest(TreeNode *root, int &result, int n)
{
if (!root)
return;
if (root->val == n)
{
// so since n exists itself in the binary tree
result = root->val;
return;
}
// since current node is less than n we can move right
else if (root->val < n)
{
// but for now, maximum valus less than n is current node value
// so update that
result = root->val;
searchLargest(root->right, result, n);
}
// current node value is more than n, so move to left,
// till now maxium is same as what we have already(INT_MIN)
else
return searchLargest(root->left, result, n);
}
int LargestNumberlessThanEqualToN(TreeNode *root, int n)
{
int result = INT_MIN;
searchLargest(root, result, n);
return result;
}
int main()
{
TreeNode *root = new TreeNode(16);
root->left = new TreeNode(3);
root->left->right = new TreeNode(13);
root->left->right->left = new TreeNode(10);
root->right = new TreeNode(20);
root->right->left = new TreeNode(18);
int n = 15;
int maximum = LargestNumberlessThanEqualToN(root, n);
if (maximum != INT_MIN)
cout << "Largest value in the BST less than 15 is: " << maximum << endl;
else
cout << "There is no largest value less than or equal to N\n";
n = 1;
maximum = LargestNumberlessThanEqualToN(root, n);
if (maximum != INT_MIN)
cout << "Largest value in the BST less than 15 is: " << maximum << endl;
else
cout << "There is no largest value less than or equal to N\n";
return 0;
}
Output
Largest value in the BST less than 15 is: 13
There is no largest value less than or equal to N
0 Comments