Displaying Trees

Printing Trees to Terminal

As a final capability in our MyTreeNode<T> class, we will implement a way to display our trees as printed output to the terminal. Drawing branches just with text is very difficult! So instead, we will simply display a node by printing its item, then display its children by indenting their items one tab compared to the original node. And then indenting their children’s items two tabs, etc.

For example, the tree:

would be printed as:

150
	151
		275
		241
			210
				341
			364
			374
		280
			383

We can implement this functionality by using a recursive function similar to the final method of Warmup 1 where we printed indented lists. In particular, implement a private method called print that:

  1. Takes one parameter: a String prefix that contains any needed tab indents
  2. Prints the prefix, followed by the contents of the item instance variable
  3. Recurses on the children of the node to also print their item and children

As a helpful hint, the String “\t” represents a single tab character in Java.

Because we don’t want any other code to have to think about the tab prefixes to use when printing, write a second public method called print that takes no parameters and simply calls your other print method as a helper method (with the appropriate first prefix). Developers should use this second, parameterless version of print in their code whenever they want to print a node (preferably only calling print on the root of a tree to print the entire tree).

Testing our Print Method

Finally, we want to verify that our print methods are implemented properly. Unfortunately, since they use System.out.println, instead of returning values, we cannot use a unit test here.

Instead, create a public static void main(String[] args) method in your MyTreeNode.java file, create a tree, call the public print method on that tree, and use the output in the terminal to verify if the methods were implemented properly (debug if necessary). As a possible strategy, you might want to create the above tree in code and verify that calling the public version of the print method generates the example printed output above.

Committing Your Progress

Don’t forget to frequently save your progress periodically to GitHub using the add, commit, and push commands with git.