0
0
DSA Javascriptprogramming~30 mins

Floor and Ceil in BST in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Floor and Ceil in BST
📖 Scenario: You are working with a phone book application that stores contacts in a Binary Search Tree (BST) by their phone numbers. You want to find the closest existing phone number that is less than or equal to a given number (floor), and the closest existing phone number that is greater than or equal to a given number (ceil).
🎯 Goal: Build functions to find the floor and ceil values for a given number in a BST of phone numbers.
📋 What You'll Learn
Create a BST with given phone numbers
Add a variable for the target phone number to search floor and ceil for
Write functions to find floor and ceil values in the BST
Print the floor and ceil values for the target number
💡 Why This Matters
🌍 Real World
Finding floor and ceil values in BSTs is useful in phone book lookups, database indexing, and range queries where you want closest matches.
💼 Career
Understanding BST operations and floor/ceil logic is important for software engineers working with search algorithms, databases, and performance optimization.
Progress0 / 4 steps
1
Create the BST with phone numbers
Create a class called Node with value, left, and right properties. Then create a BST by creating nodes with these exact phone numbers: 50, 30, 70, 20, 40, 60, 80. Link them to form a valid BST.
DSA Javascript
Hint

Define a Node class with value, left, and right. Then create nodes and assign left and right to build the BST.

2
Add the target number variable
Create a variable called target and set it to 65. This is the number you will find floor and ceil for in the BST.
DSA Javascript
Hint

Just create a constant variable named target and assign 65.

3
Write functions to find floor and ceil in BST
Write two functions: findFloor(root, target) and findCeil(root, target). Each function takes the BST root and the target number. findFloor returns the greatest value in BST less than or equal to target or null if none. findCeil returns the smallest value in BST greater than or equal to target or null if none.
DSA Javascript
Hint

Use a loop starting at root. For floor, go left if current value > target, else update floor and go right. For ceil, go right if current value < target, else update ceil and go left.

4
Print the floor and ceil values
Use console.log to print the floor and ceil values for target using findFloor(root, target) and findCeil(root, target). Print exactly like this: Floor: 60 and Ceil: 70.
DSA Javascript
Hint

Use console.log to print floor and ceil with the exact format: Floor: value and Ceil: value.