sd2205 sd2205 - 6 months ago 32
Java Question

toString method for binary search tree

Please help me to fixed my code. I'm stuck!!

For the to String method, the string should be formatted as {currentData, leftSubtree, rightSubtree}
An empty tree should return an empty set of brackets {}.

for the Junit test I'm getting:

Expected: {5, {0, {-5, {}, {}}, {3, {}, {}}}, {10, {7, {}, {}}, {13, {}, {}}}}
Actual: {5, {0, {-5, {}, {3, {}, {}, {10, {7, {}, {13, {}, {}, {}}


This is my code:

public String toString() {
StringBuffer string = new StringBuffer("{");
toString(root, string);
string.append("}");
return string.toString();
}

private void toString(BSTNode<T> node, StringBuffer string) {

if (node != null) {
string.append(node.getData());
if (node.getLeft() != null) {
string.append(", " + "{");
toString(node.getLeft(), string);
}
if (node.getRight() != null) {
string.append(", " + "{");
toString(node.getRight(), string);
}
}
string.append(", {}");
}


Thanks!!

Answer

I think, you should wrap the line string.append(", {}"); into else branch.

if(node != null) {
    ...
} else {
   string.append(", {}");
}

Otherwise, it will be executed regardless of the node != null condition.

The same you need to do with node.getLeft() and node.getRigth():

if (node.getLeft() != null) {
    string.append(", " + "{");
    toString(node.getLeft(), string);
    string.append("}");
} else {
    string.append(", " + "{}");
}
if (node.getRight() != null) {
    string.append(", " + "{");
    toString(node.getRight(), string);
    string.append("}");
} else {
    string.append(", " + "{}");
}
Comments