Important Notice:

Practice-It will be discontinued as of November 1st, 2024. After this date, the website will remain online for a transitional period, but login will be restricted to University of Washington NetID authentication. This marks the next phase towards the platform's full retirement. Thank you for your use and support of the application over the years.

If you are looking for an alternative, a similar tool, CodeStepByStep, was developed independently by the original author of Practice-It, and is available at codestepbystep.com**

logo Practice-It logo

toString

Related Links:
Author: Robert Baxter

Write a method toString2 for a binary tree of integers. (On your section handout the method is called toString, but Practice-It needs you to call your method toString2 because toString is already used for another purpose.) The method should return "empty" for an empty tree. For a leaf node, it should return the data in the node as a String. For a branch node, it should return a parenthesized String that has three elements separated by commas:

  1. The data at the root.
  2. A String representation of the left subtree.
  3. A String representation of the right subtree.

For example, if a variable tree stores a reference to the following tree:

          +---+
          | 2 |
          +---+
         /     \
     +---+     +---+
     | 8 |     | 1 |
     +---+     +---+
    /         /     \
+---+     +---+     +---+
| 0 |     | 7 |     | 6 |
+---+     +---+     +---+
         /               \
     +---+               +---+
     | 4 |               | 9 |
     +---+               +---+

Then the call tree.toString2(); should return the following String:

"(2, (8, 0, empty), (1, (7, 4, empty), (6, empty, 9)))"

The quotes above are used to indicate that this is a String but should not be included in the String you return.

(Note: On the original section handout, this method is called toString, but Practice-It already defines a toString method for IntTree for use in other problems, so this method must be called toString2 to avoid a conflict.)

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.