I have a toString method, which should return a string representing the whole binary search tree in order. I've come this far, but this is just printing out the numbers in order, and the toString method just returns the value of rootNode of course. I don't know how I should solve this.
@Override
public String toString() {
if (rootNode == null){
return "";
}
else {
return inorder(rootNode.data);
}
}
/**
* @param root
*/
public String inorder(Node<T> root){
if (root != null){
inorder(root.left);
System.out.println(root.value + " ");
inorder(root.right);
}
}
I've been stuck with this problem for hours.
Maybe you can try this
@Override
public String toString()
{
java.lang.StringBuilder toReturn = new java.lang.StringBuilder();
if (rootNode == null){
return "";
}
else{
inorder(rootNode.data , toReturn);
}
return toReturn.toString();
}
/**
* @param root
*/
public void inorder(Node<T> root , java.lang.StringBuilder treeLikeStringBuilder){
if (root != null){
inorder(root.left);
System.out.println(root.value + " ");
treeLikeStringBuilder.append( root.value.toString() + " " );
inorder(root.right);
}
}
inorder(Node , StringBuilder) signature would instead help in building a String like structure for the inorder traversal, so that toString() could return that String inorder travsersal, also StringBuilder is used so that the changes made to the MUTABLE StringBuilder passed as argument (StringBuilder toReturn) to method inorder(Node , StringBuilder) would reflect the changes back in the toString() method, hope it helps??