logo CodeStepByStep logo

removeLeaves

Language/Type: Java binary trees x=change(x)

Write a method named removeLeaves that removes the leaves from a tree. A leaf is a node that has empty (null) left and right subtrees. Your method accepts as its parameter a TreeNode representing the root of the tree and returns the tree's new root.

For example, suppose a variable tree refers to the root of the first tree below:

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

The call of removeLeaves(tree) should remove the four leaves from the tree (the nodes with data values 1, 4, 6, and 0) returning the tree shown below.

(7 (3) (9 / (8)))

If your method is called on an empty tree, you should return null.

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.