二进制搜索字符串

BinarySearch toString

我想像在 TreeSet 中一样创建一个 toString。 例如,我的 toString 将打印如下内容:

Student{name='student1', dateOfBirth=2003-04-01, details='none'}, Student{name='student2', dateOfBirth=1999-05-11, details='none'}, 

但我想要这样的东西:

[Student{name='student1', dateOfBirth=2003-04-01, details='none'}, Student{name='student2', dateOfBirth=1999-05-11, details='none'}]

我的代码:

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

    private void inorderPrint(Node root, StringBuffer stringBuffer) {

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

要添加额外的字符,例如 [ , ],您可以在 inOrder 遍历中使用附加条件。

示例代码:

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

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