【问题标题】:Java: Method to convert binary search tree into a stringJava:将二叉搜索树转换为字符串的方法
【发布时间】: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 方法是错误的,但我在字符串科学中不是很常用。

【问题讨论】:

  • line from linealNotation is notlinearize修改(concact不会改变String的内容),这意味着无论你在哪里使用来自linealNotation的返回值,它将是一个空字符串。
  • 为了更详细地说明之前的 cmets,Strings 在 Java 中是 /immutable/,您不能在其中“插入”任何内容或以任何方式更改其内容。您只能根据旧内容制作新内容。

标签: java string binary-search-tree


【解决方案1】:

String 是不可变的 - 您无法更改其内容。 concat 方法返回一个新的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(")");
}

【讨论】:

    【解决方案2】:

    您应该将行变量的数据类型设为 StringBuffer 或 StringBuilder。

    因为字符串在 Java 中是不可变的,所以当你尝试 concat(在此上下文中表示变异)时,它不会起作用。

    或者,如果你坚持使用字符串,那么你应该让返回的连接字符串再次引用行,即

    line = line.concat("blahblah");
    

    但效率略低。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多