You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为二分搜索树实现与TreeSet格式一致的toString方法

你现有代码的问题有两个:

  1. 没有用[和]包裹整个输出内容
  2. 每个元素后都拼接了, ,导致最后一个元素末尾多了多余的分隔符

改动最小的实现方案

只需要修改toString方法,加首尾括号并删除末尾多余分隔符即可,适配空集合场景:

public String toString() {
    StringBuffer string = new StringBuffer();
    string.append("[");
    inorderPrint(root, string);
    // 存在元素时删除末尾多余的", "
    if (string.length() > 1) {
        string.delete(string.length() - 2, string.length());
    }
    string.append("]");
    return string.toString();
}

private void inorderPrint(Node root, StringBuffer stringBuffer) {
    if (root != null) {
        inorderPrint(root.left, stringBuffer);
        stringBuffer.append(root.value.toString()).append(", ");
        inorderPrint(root.right, stringBuffer);
    }
}

性能更优的实现方案

如果不想做末尾字符删除操作,可以新增标记位判断是否是第一个元素,分隔符加在元素前,避免生成多余字符:

public String toString() {
    StringBuffer string = new StringBuffer("[");
    AtomicBoolean isFirstElement = new AtomicBoolean(true);
    inorderPrint(root, string, isFirstElement);
    string.append("]");
    return string.toString();
}

private void inorderPrint(Node root, StringBuffer stringBuffer, AtomicBoolean isFirstElement) {
    if (root != null) {
        inorderPrint(root.left, stringBuffer, isFirstElement);
        // 非第一个元素先加分隔符
        if (isFirstElement.get()) {
            isFirstElement.set(false);
        } else {
            stringBuffer.append(", ");
        }
        stringBuffer.append(root.value.toString());
        inorderPrint(root.right, stringBuffer, isFirstElement);
    }
}

内容的提问来源于stack exchange,提问作者Imatabil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:06:03