Largest number in BST which is less than or equal to N

We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N.

Examples:For the above given binary search tree-

Input : N = 24
Output :result = 21
(searching for 24 will be like-5-12-21)

Input  : N = 4
Output : result = 3
(searching for 4 will be like-5->2->3)

We follow recursive approach for solving this problem. We start searching for element from root node. If we reach a leaf and its value is greater than N, element does not exist so return -1. Else if node’s value is less than or equal to N and right value is NULL or greater than N, then return the node value as it will be the answer.
Otherwise if node’s value is greater than N, then search for the element in the left subtree else search for the element in the right subtree by calling the same function by passing the left or right values accordingly.

int BinarySearchTree::findMaxForN(TreeNode *root, int N) {
    if (!root) return -1;
    if (root->left == NULL && root->right == NULL && root->val > N) return -1;

    if ((root->val <= N && root->right == NULL) ||
        (root->val <= N && root->right->val > N))
        return root->val;

    if (root->val >= N)
        return findMaxForN(root->left, N);
    else
        return findMaxForN(root->right, N);
}

results matching ""

    No results matching ""