logo Practice-It logo

BJP5 Exercise 17.12: removeLeaves

Related Links:
Author: Robert Baxter (on 2019/09/19)

Write a method removeLeaves that removes the leaves from a tree. A leaf node that has empty left and right subtrees. If a variable tree refers to the first tree below, the call of tree.removeLeaves(); should remove the four leaves from the tree (the nodes with data values 1, 4, 6, and 0) leaving the next tree shown below.

A second call on the method would eliminate the two leaves in this tree (the nodes with data values 3 and 8), shown in the third tree below. A third call would eliminate the one leaf with data value 9, and a fourth call would leave an empty tree because the previous tree was exactly one leaf node. If your method is called on an empty tree, the method does not change the tree because there are no nodes of any kind (leaf or not).

Call # Tree
(before call) 0
               +---+
               | 7 |
           ___ +---+ ___
         /               \
     +---+               +---+
     | 3 |               | 9 |
     +---+               +---+
    /     \             /     \
+---+     +---+     +---+     +---+
| 1 |     | 4 |     | 6 |     | 8 |
+---+     +---+     +---+     +---+
                                   \
                                   +---+
                                   | 0 |
                                   +---+
tree.removeLeaves(); 1
               +---+
               | 7 |
               +---+
              /     \
          +---+     +---+
          | 3 |     | 9 |
          +---+     +---+
                         \
                         +---+
                         | 8 |
                         +---+
2
               +---+
               | 7 |
               +---+
                    \
                    +---+
                    | 9 |
                    +---+
3
               +---+
               | 7 |
               +---+
4
               null

Assume that you are adding this method to the IntTree class as defined below:

public class IntTree {
    private IntTreeNode overallRoot;
    ...
}
Type your solution here:


This is a partial class problem. Submit code that will become part of an existing Java class as described. You do not need to write the complete class, just the portion described in the problem.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.