Search code examples
javabinary-treebinary-search-tree

BinarySearch toString


I want to make a toString just like in the TreeSet. For example my toString will print something like this:

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

But i want something like that:

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

My code:

 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);
        }
    }

Solution

  • For adding extra characters like [ , ] you can use additional condition within inOrder traverse.

    Sample code:

    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);
        }
    }