THINK FIRST·CODE LATER

← All labs

Balance factors and the four rotation cases

Problem

Write BalanceFactors. Insert the input keys into a plain BST (no rebalancing). Then print, in increasing key order, each node's height (a leaf has height 0) and balance factor = height(left) − height(right), marking nodes with |balance| > 1.

If the tree is not an AVL tree, print how many nodes violate the condition, the key of the deepest violating node (where an AVL tree would rotate first) and which case it is: LL (one right rotation), RR (one left rotation), LR or RL (double rotations).

For the input

30 20 10

the program prints

BST with 3 keys, height 2
  key 10: height 0, balance 0
  key 20: height 1, balance +1
  key 30: height 2, balance +2  <-- violates AVL
1 unbalanced node(s); fix first at key 30
Case LL: one right rotation

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

30 20 10
What your program must print for d13-3-data-1.txt
BST with 3 keys, height 2
  key 10: height 0, balance 0
  key 20: height 1, balance +1
  key 30: height 2, balance +2  <-- violates AVL
1 unbalanced node(s); fix first at key 30
Case LL: one right rotation

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

Windows PowerShell does not understand <:

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