712690. Floor in BST

Medium

Here is a detailed Markdown blog post for the "Floor in BST" problem:

Floor in BST

Summary

Given a Binary Search Tree (BST) and a target value, find the floor of the target value. The floor of a number in a sorted array or tree is the largest number less than or equal to the given number. This problem involves working with binary search trees, which are fundamental data structures in computer science.

Detailed Explanation

To solve this problem, we need to traverse the BST and keep track of the largest value smaller than our target value. We can do this using an in-order traversal of the tree, where we visit each node in ascending order.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable floor to negative infinity.
  2. Traverse the BST in-order (left-root-right).
  3. For each node in the tree:
    • If the node's value is less than our target, update floor to be the current node's value.
  4. Return floor.

Here's an ASCII art diagram of the traversal:

4

/
2 6 /
5 7

In this example, if we're searching for the floor of 5, our traversal would be: 2 -> 4 -> 5. The largest value smaller than or equal to 5 is 4, so that's our answer.

Time complexity: O(h), where h is the height of the tree. This is because we need to traverse the entire tree in the worst case. Space complexity: O(1), since we're not using any extra space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public int findFloor(Node root, int target) {
    int floor = Integer.MIN_VALUE;
    inOrderTraversal(root, target, floor);
    return floor;
}

private void inOrderTraversal(Node node, int target, int floor) {
    if (node == null) return;

    inOrderTraversal(node.left, target, floor);

    if (node.val <= target) {
        floor = node.val;
    }

    inOrderTraversal(node.right, target, floor);
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.