THINK FIRST·CODE LATER

← All labs

Build a BST and print its traversals

Problem

Read integer keys, insert them one by one (in input order) into an initially empty binary search tree, and print the tree's size, its four traversals and its height.

Duplicates: a key that is already in the tree is ignored (the tree is a set).

Input. The first line holds n (n ≥ 0), the number of keys; then n integers follow.

Output. Exactly these six lines, each traversal's keys separated by single spaces:

Size: <number of distinct keys>
In-order: <keys>
Pre-order: <keys>
Post-order: <keys>
Level-order: <keys>
Height: <height in edges>

For an empty tree each traversal line shows (empty) (e.g. In-order: (empty)) and the height is -1. A single node has height 0.

Example.

Input:
6
5 3 5 8 3 1

Output:
Size: 4
In-order: 1 3 5 8
Pre-order: 5 3 1 8
Post-order: 1 3 8 5
Level-order: 5 3 8 1
Height: 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-1-data-1.txt

6
5 3 5 8 3 1
What your program must print for d12-1-data-1.txt
Size: 4
In-order: 1 3 5 8
Pre-order: 5 3 1 8
Post-order: 1 3 8 5
Level-order: 5 3 8 1
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 < d12-1-data-1.txt

Windows PowerShell does not understand <:

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