712690. Floor in BST
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:
- Initialize a variable
floorto negative infinity. - Traverse the BST in-order (left-root-right).
- For each node in the tree:
- If the node's value is less than our target, update
floorto be the current node's value.
- If the node's value is less than our target, update
- 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
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);
}