beyondgrader.com Logo
DemoBrowseAboutTeamLogin

BinaryTree Values at Level (int)

Geoffrey Challen // 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.