MasterGeekMX MasterGeekMX - 28 days ago 11
Java Question

Java: Method to convert binary search tree into a string

I'm working with a method wich converts a binary tree into a string with the tree in parentesis notation. Here is what I got so far:

//both of this methods are in the tree class,
//so every other method or variable are directly visible

/*this method creates the string, and then
* calls another method to fill the string with the
* tree in pre-order, and then retuns the string
alredy filled.*/

public String linealNotation(){
String line = new String();
linearize(line,root); //root is the Node wich starts the tree.
return line;
}
//this method is the one with fills the string with an pre-order reading.
private void linearize(String line, Node n){
if(n==null)
return;
line.concat(""+n.data); //this is my cry-blood way to insert the
line.concat("("); //int stored in the node into the string
linearize(line,n.left);
line.concat(",");
linearize(line,n.right);
line.concat(")");
}


But when I print the string returned by my method, nothing appears, and String.length() returns me a zero.

Maybe the concat ways in my method are wrong, but I'm not very used in strings sciences.

Answer

A String is immutable - you can't change its contents. The concat method returns a new String, rather than adding to an existing one.

What you want to do is use StringBuilder instead of String. Your code should look like this. Note

  • the use of toString in the linealNotation method, to convert the StringBuilder back into a String.
  • the use of the append method to concatenate the data together.

.

public String linealNotation(){
    StringBuffer line = new StringBuffer();
    linearize(line,root); 
    return line.toString();
}


private void linearize(StringBuilder line, Node n){
    if (n==null) {
        return;
    }
    line.append(n.data); 
    line.append("(");       
    linearize(line,n.left);
    line.append(",");
    linearize(line,n.right);
    line.append(")");
}
Comments