2012-05-21 49 views
3

我有一个轻微的算法问题。我想我错过了一些东西,但不能确切地弄清楚什么。递归方法在每一步都返回一个字符串?

我想步行到一个包含字符串的树并用一个唯一的字符串出去。

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

tree example

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

  • 布尔运算符(OR,NOT,AND)=> BE
  • 其他运营商(如=)=> QO
  • 叶(最后元素)=> LEAF

我想的东西落得像这样:

"LEAF QO LEAF BE LEAF QO LEAF " 

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

public class 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; 
} 
+0

哼哼,好像这里有一些食物给我:http:// stackoverflow。com/questions/5077216/returns-an-inorder-string-of-a-tree – jlengrand

回答

3

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

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

+0

明白了,我确实缺少这部分内容:“然后,将递归调用的结果与上面的字符串连接起来。谢谢 – jlengrand

相关问题