THINK FIRST·CODE LATER

← All labs

The best-shaped BST from sorted keys

Problem

Inserting sorted keys one by one gives the worst BST: a chain. Write BalancedBst: read n and n keys in increasing order, and

  1. insert them one by one into a plain BST and print its height;
  2. build a balanced BST with a recursive build(sorted, low, high) that makes the middle element ((low + high) / 2) the root and builds the two halves as subtrees; print its height;
  3. print the balanced tree level by level with a queue (one line per level);
  4. print the smallest height any binary tree with n keys can have.

A single node has height 0.

For the input

7
10 20 30 40 50 60 70

the program prints

Inserting in sorted order: height 6
Built from the middle: height 2
  level 0: 40
  level 1: 20 60
  level 2: 10 30 50 70
Smallest possible height for 7 keys: 2

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-6-data-1.txt

7
10 20 30 40 50 60 70
What your program must print for d12-6-data-1.txt
Inserting in sorted order: height 6
Built from the middle: height 2
  level 0: 40
  level 1: 20 60
  level 2: 10 30 50 70
Smallest possible height for 7 keys: 2

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-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content d12-6-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.