THINK FIRST·CODE LATER

← All labs

Build an AVL Tree

Problem

Read an integer n, then n integer keys. Insert them in order into an initially empty AVL tree (duplicates are ignored). Then print the pre-order traversal (keys separated by single spaces) and the height of the tree. The height of an empty tree is −1 and of a single node 0. If the tree is empty, print (empty) instead of the keys.

Because the rotations change the shape, the pre-order traversal shows whether you rebalanced correctly.

Input:

5 10 20 30 40 50

Output:

Pre-order: 20 10 40 30 50
Height: 2

Empty input (0):

Pre-order: (empty)
Height: -1

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.

d13-1-data-1.txt

5 10 20 30 40 50
What your program must print for d13-1-data-1.txt
Pre-order: 20 10 40 30 50
Height: 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 < d13-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content d13-1-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.