Binary Search Tree: Recursive toString

22,969

How do you want to show them?

You need to append the Strings, for example.

private String toString(BSTnode root)
{
    StringBuilder builder = new StringBuilder();
    if (root == null)
        return "";
    builder.append(toString(root._left));
    builder.append(toString(root._right));
    return builder.append(root._data.toString()).toString();
}

or just use a concatenation on strings.

private String toString(BSTnode root)
{
    String result = "";
    if (root == null)
        return "";
    result += toString(root._left);
    result += toString(root._right);
    result += root._data.toString()
    return result;
}
Share:
22,969
user2810123
Author by

user2810123

Updated on May 06, 2021

Comments

  • user2810123
    user2810123 about 3 years

    It only prints out one item. It is suppose to print the contents of the tree in ascending order

    public String toString()
    {
        return toString (_root);
    }
    private String toString(BSTnode root)
    {
        if (root == null)
            return "";
        toString(root._left);
        toString(root._right);
        return root._data.toString();
    }
    
  • Janac Meena
    Janac Meena about 4 years
    How would I go about adding a comma after each char in the string? i.e. "a,b,c,d,e,f"