[英]Java: Method to convert binary search tree into a string
我正在使用一種方法,該方法將二叉樹轉換為帶有括號表示法的樹的字符串。 這是我到目前為止所得到的:
//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 returns the string
already filled.*/
public String linealNotation(){
String line = new String();
linearize(line,root); //root is the Node which 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(")");
}
但是當我打印我的方法返回的字符串時,什么也沒有出現,並且 String.length() 返回零。
也許我的方法中的 concat 方式是錯誤的,但我不太熟悉弦科學。
String
是不可變的——你不能改變它的內容。 concat
方法返回一個新的String
,而不是添加到現有的String
。
您想要做的是使用StringBuilder
而不是String
。 您的代碼應如下所示。 注意
linealNotation
方法中使用toString
,將StringBuilder
轉換回String
。append
方法將數據連接在一起。.
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(")");
}
您應該將行變量的數據類型設為 StringBuffer 或 StringBuilder。
因為字符串在 Java 中是不可變的,所以當您嘗試連接(在此上下文中表示變異)時,它將不起作用。
或者,如果你堅持使用字符串,那么你應該讓返回的 concat 字符串再次引用行,即
line = line.concat("blahblah");
但是效率稍低。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.