我有 2 个类,NonEmptyTree 和 EmptyTree 实现了 Tree 接口(interface)。 NonEmptyTree 类中的 toString()
方法应返回一个字符串:key=>value key=>value key>value
等...
我不知道如何删除结果末尾的最后一个空格。
编辑:我不能使用 String 类中的任何方法,也不能将任何内容与 null 进行比较。
public String toString() {
String result = "";
result+=(this.left.toString());
result+=this.key;
result+="=>";
result+=this.value;
result+=" ";
result+=this.right.toString();
return result;
}
我尝试为该类添加一个变量,指示 NonEmptyTree 实例是否是当前树中最大的实例,但控制台显示相同的字符串。
例如,字符串如下所示:
"7=>seven 10=>ten 12=>twelve 15=>fifteen 16=>sixteen 17=>seventeen 20=>twenty 30=>thirty "
如有任何帮助,我们将不胜感激。谢谢
最佳答案
使用String.trim()
:
return result.trim()
顺便说一句。如果您进行大量 String
添加,最好使用 StringBuilder
及其方法 append()
而不是添加多个 String
带有 +
的 code>。
关于java - 多态二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5526337/