【发布时间】:2016-11-06 04:56:41
【问题描述】:
我正在使用一种将二叉树转换为字符串的方法,该树用括号表示法。这是我到目前为止得到的:
//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 方法是错误的,但我在字符串科学中不是很常用。
【问题讨论】:
-
linefromlinealNotationis not 被linearize修改(concact不会改变String的内容),这意味着无论你在哪里使用来自linealNotation的返回值,它将是一个空字符串。 -
为了更详细地说明之前的 cmets,
Strings 在 Java 中是 /immutable/,您不能在其中“插入”任何内容或以任何方式更改其内容。您只能根据旧内容制作新内容。
标签: java string binary-search-tree