SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Binary Trees
Exercise:
Exercises
Question:9 | ISBN:9780136091813 | Edition: 2

Question

Write a toString method for a binary tree of integers. 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: the data at the root, a string representation of the left subtree, and then a string representation of the right subtree. For example, if a variable t refers to reference tree #2, then the call t.toString() should return the following String (without the surrounding quotes):

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

Add the following method to the IntTree class from this chapter. You may define additional private methods to implement your public method if necessary. Several problem descriptions refer to the following reference binary trees:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of toString method:


	public String toString()
	{
		return toString(overallRoot);
	}

	private String toString(IntTreeNode root)
	{
		String result = "";
		
		if(root == null)
		{
			result = "empty";
		}
		else
		{
			result = result + root.data;
			
			if(root.left != null || root.right != null)
			{
				result = "(" + result + ", " 
							+ toString(root.left);
				result = result + ", " 
							+ toString(root.right) + ")";
			}
		}
		
		return result;
	}

0 0

Discussions

Post the discussion to improve the above solution.