logo CodeStepByStep logo

toString

Language/Type: Java binary trees
Related Links:

Write a method named toString that returns a string representation of a binary tree of integers. Your method accepts as its parameter a TreeNode that refers to the root of the tree. 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 named tree refers to the root of the following tree:

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

Then the call toString(tree) 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.

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.