THINK FIRST·CODE LATER

← All labs

BST queries: floor, ceiling and rank

Problem

Write BstQueries with your own BST whose nodes also store the size of their subtree. Read n and n distinct keys (inserted in that order), then query values x until the end of input. For each x print:

  • floor(x): the largest key ≤ x;
  • ceiling(x): the smallest key ≥ x;
  • rank(x): the number of keys smaller than x (use the subtree sizes — do not traverse the whole tree).

For the input

7
50 30 70 20 40 60 80
45 50 10 95 60

the program prints

Keys in the tree: 7
x = 45: floor 40, ceiling 50, rank 3
x = 50: floor 50, ceiling 50, rank 3
x = 10: floor none, ceiling 20, rank 0
x = 95: floor 80, ceiling none, rank 7
x = 60: floor 60, ceiling 60, rank 4

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d12-3-data-1.txt

7
50 30 70 20 40 60 80
45 50 10 95 60
What your program must print for d12-3-data-1.txt
Keys in the tree: 7
x = 45: floor 40, ceiling 50, rank 3
x = 50: floor 50, ceiling 50, rank 3
x = 10: floor none, ceiling 20, rank 0
x = 95: floor 80, ceiling none, rank 7
x = 60: floor 60, ceiling 60, rank 4

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d12-3-data-1.txt

Windows PowerShell does not understand <:

Get-Content d12-3-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.