logo CodeStepByStep logo

printLeaves

Language/Type: Java binary trees

Write a method named printLeaves that outputs the leaves of a binary tree of integers from right to left. Your method accepts as its parameter a TreeNode that refers to the root of the tree. For example, if a variable tree refers to the root of the following tree:

(2 (8 (0)) (1 (7 (4)) (6 / (9))))

Then the call of printLeaves(tree); should produce the following output:

leaves: 9 4 0

If the tree does not have any leaves (an empty tree), simply print:

no leaves

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.