THINK FIRST·CODE LATER

← All labs

The shape of a BST: height, leaves and levels

Problem

Write BstShape: insert the integers of the input in a binary search tree (duplicates are ignored), then print

  • the number of nodes and the height (the number of nodes on the longest path from the root to a leaf; 0 for an empty tree);
  • the number of leaves and of internal nodes;
  • the tree level by level (breadth-first traversal with a queue), one line per level;
  • the size of the widest level.

height, size and leaves are recursive; the level-by-level traversal is not. For the input

50 30 70 20 40 60 80 35 45 65

the program prints

Nodes: 10, height: 4
Leaves: 5, internal nodes: 5
Level 0: 50
Level 1: 30 70
Level 2: 20 40 60 80
Level 3: 35 45 65
Widest level: 4 node(s)

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

50 30 70 20 40 60 80 35 45 65
What your program must print for d12-7-data-1.txt
Nodes: 10, height: 4
Leaves: 5, internal nodes: 5
Level 0: 50
Level 1: 30 70
Level 2: 20 40 60 80
Level 3: 35 45 65
Widest level: 4 node(s)

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

Windows PowerShell does not understand <:

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