Kotlinlearncs.online LogoJava
Return to List

Test Writing: BinaryTree Values at Level (int)

Created By: Geoffrey Challen
/ Version: 2021.4.0

Create a public class named BinaryTreeValuesAtLevel providing a single static method valuesAtLevel. valuesAtLevel accepts a BinaryTree<Integer> (from cs125.trees) and a level as an int. It should return, as a List<Integer>, all the values in the passed tree that are at the passed level, sorted in ascending order. If the passed tree is null, or the level is negative, you should throw an IllegalArgumentException.

The level corresponds to the depth of the node in the tree. So the root node is at level 0, its children are at level 1, its children's children are at level 2, etc.

To complete this question you probably need a helper method. Our suggestion is that the main valuesAtLevel create the list, begin the recursion, and sort the result. (Just use a built-in sort.) Your recursive method will need to track both the current level in the tree and the target level. Once the target level is reached, the current node's value should be added and the recursion can stop. You will also want to pass the list created by your main method.

Test Design Challenge

You're challenge is to write tests for this problem described above.

  • Provide a public class named TestBinaryTreeValuesAtLevel with a single non-private class method named test that accepts no arguments and does not return a value.
  • If the implementation of the class described above is incorrect, your test method should throw an exception.
  • If it is correct, do not throw an exception.
  • You may want to use Java's assert method