THINK FIRST·CODE LATER

← All labs

Range queries, k-th smallest and BST validation

Problem

Write BstRange. Read n and n keys into a BST, then low high k. Print:

  1. the keys in [low, high] in increasing order, using an in-order traversal that prunes subtrees that cannot contain such keys (go left only if low < key, right only if key < high), and the number of nodes visited (non-null nodes on which the method is called);
  2. the k-th smallest key (none if k > n), by an in-order walk that stops early;
  3. the height (a single node has height 0) and the result of isBst, which checks that every key lies strictly between the bounds inherited from its ancestors;
  4. if the root has a left child: set that child's key to root.key + 1 and run isBst again.

For the input

9
50 30 70 20 40 60 80 35 45
33 62 3

the program prints

Keys in [33, 62]: [35, 40, 45, 50, 60]
Nodes visited: 7 of 9
Smallest #3: 35
Height: 3, valid BST: true
After corrupting the left child: valid BST: false

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

9
50 30 70 20 40 60 80 35 45
33 62 3
What your program must print for d12-5-data-1.txt
Keys in [33, 62]: [35, 40, 45, 50, 60]
Nodes visited: 7 of 9
Smallest #3: 35
Height: 3, valid BST: true
After corrupting the left child: valid BST: false

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

Windows PowerShell does not understand <:

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