logo CodeStepByStep logo

printLevel

Language/Type: Java binary trees

Write a method named printLevel that prints the data values at a given level of a binary tree from left to right, one per line. Your method accepts as its parameters a TreeNode referring to the root of the tree, and an integer parameter n representing the level to print. We will use the convention that the tree's root is at level 1, that its children are at level 2, and so on. For example, if a variable tree refers to the root of the following tree:

(12 (19 (11) (14 (10))) (93 / (15)))

Then the call printLevel(tree, 3); would produce the following output:

11
14
15

If there are no nodes at the given level, your method should produce no output. Your method should throw an IllegalArgumentException if passed a value for a level n that is less than 1.

Assume that you are interacting with TreeNodes as defined below:

public class TreeNode {
    public int data;
    public TreeNode left;
    public TreeNode right;
    
    public TreeNode() { ... }
    public TreeNode(int data) { ... }
    public TreeNode(int data, TreeNode left, TreeNode right) { ... }
}
Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.