The “floor” of a given value is the largest value in the tree that is less than or equal to the given value. In other words, it’s the “closest” value in the tree that is not greater than the given value.

C++ Solution:

#include <iostream>
using namespace std;

class TreeNode {
public:
    int data;
    TreeNode* left;
    TreeNode* right;

    TreeNode(int val) {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

class BST {
private:
    TreeNode* root;

    int floorRecursive(TreeNode* root, int val) {
        if (root == nullptr) {
            return -1;  // No floor value found
        }

        if (root->data == val) {
            return val;  // The current node's value is the floor
        } else if (root->data > val) {
            return floorRecursive(root->left, val);  // Search in the left subtree
        }

        // The potential floor value is in the right subtree
        int floorValue = floorRecursive(root->right, val);
        return (floorValue <= val && floorValue != -1) ? floorValue : root->data;
    }

public:
    BST() {
        root = nullptr;
    }

    // Other functions like insert and remove go here

    int floor(int val) {
        return floorRecursive(root, val);
    }
};

int main() {
    BST bst;

    bst.insert(15);
    bst.insert(8);
    bst.insert(20);
    bst.insert(12);
    bst.insert(25);

    int floorValue = bst.floor(16);  // Finding the floor of 16
    if (floorValue != -1) {
        cout << "Floor of 16 is: " << floorValue << endl;
    } else {
        cout << "No floor value found." << endl;
    }

    return 0;
}

Code Explanation:

floorRecursive function recursively searches for the floor value in the BST.

  • If the current node’s value is equal to the given value, it means the floor value is found and is equal to the current value.
  • If the current node’s value is greater than the given value, the potential floor value is in the left subtree.
  • If the current node’s value is less than the given value, the potential floor value is either in the right subtree or is the current node’s value.

The floor function serves as a wrapper for the recursive implementation.

In the main function, a sample BST is created, and the floor function is called to find the floor value of 16.

Time Complexity:

The time complexity of finding the floor value in a balanced BST is O(log N) on average, where N is the number of nodes. In the worst case (skewed tree), it can be O(N).

Space Complexity:

The space complexity remains O(N) due to the storage of N nodes in the tree.

The floor operation is useful for scenarios where you need to find the closest value in a BST that is not greater than a given value, such as in range queries or interval searches.