gpt4 book ai didi

java - 递归方法在每一步返回一个字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:57:23 24 4
gpt4 key购买 nike

我有一个轻微的算法问题。我想我错过了一些东西,但无法确切地弄清楚是什么。

我想走到一棵包含字符串的树,然后带着一个唯一的字符串出去。

这是我要解析的树的图形示例。

tree example

我的树将具有三种不同类型的元素:

  • boolean 运算符(OR、NOT、AND)=> BE
  • 其他运算符(如=)=> QO
  • 叶子(最后一个元素)=>叶子

我想以这样的方式结束:

"LEAF QO LEAF BE LEAF QO LEAF "

现在,我使用递归方法:我检查树的当前元素,并根据我拥有的元素类型对其子元素重新运行该方法。对于每一步,我都会填充我的最终字符串。

公共(public)类 SingleTest { static String[] booleanElements = {"or", "and", "not"};

public static void main(String[] args) throws Exception {
CommonTree tree = (CommonTree)parser.parse().getTree();

if(true){
String where = "";
printWhere(tree, where);
System.out.println(where);
}

}

/*
* Print to where tests
*/
public static boolean isBooleanElement(CommonTree t){
return Arrays.asList(booleanElements).contains(t.toString().toLowerCase());
}


public static String printWhere(CommonTree t, String where){
//---------------------
// Checking node type
//---------------------

// Boolean Element
if (isBooleanElement(t)){
// Continue parsing the tree
for ( int i = 0; i < t.getChildCount(); i++ ) {
printWhere((CommonTree)t.getChild(i), where+ "BE");
}
}

// Last element of tree (LEAF)
else if(t.getChildCount() == 0 ){
where = where + "LEAF";
}

// query operator
else{
// Continue parsing the tree
for ( int i = 0; i < t.getChildCount(); i++ ) {
printWhere((CommonTree)t.getChild(i), where + "QO");
}
}

//---------------------
return where;
}

我的问题是这段代码:

        String where = "";
System.out.println(printWhere(tree, where));

返回“”(由于我的实现,这是合乎逻辑的)。

所以我的问题是,如何才能将非空字符串作为最终输出?

希望这足够清楚谢谢你的帮助

请注意,此类仅用于测试目的,而且我知道在任何地方都放置静态是不好的做法:)

编辑:

这个问题(正如预期的那样)是由于我缺乏递归经验。这是我的最终代码:

public static String printWhere(CommonTree t, String where){
//---------------------
// Checking node type
//---------------------

// Boolean Element
if (isBooleanElement(t)){
// Continue parsing the tree
for ( int i = 0; i < t.getChildCount(); i++ ) {
where = printWhere((CommonTree)t.getChild(i), where) + "BE";
}
}

// Last element of tree (LEAF)
else if(t.getChildCount() == 0 ){
where = where + "LEAF";
}

// query operator
else{
// Continue parsing the tree
for ( int i = 0; i < t.getChildCount(); i++ ) {
where = printWhere((CommonTree)t.getChild(i), where ) + "QO";
}
}

//---------------------
return where;
}

最佳答案

问题是你的方法 printWhere 没有返回任何东西!您将值附加到新的 where 字符串,但是由于 Java 按值传递参数,因此当您离开该方法时,这个新创建的字符串将被丢弃。

使此方法返回字符串并在其末尾返回where。然后,将递归调用的结果与上一层的字符串连接起来。这就是递归的工作原理。

关于java - 递归方法在每一步返回一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10682288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com