【发布时间】:2018-04-07 05:45:01
【问题描述】:
我正在创建表达式树的中序遍历,但它没有考虑中间元素。下面是我的代码。您能否让我知道我在哪里出错以及我错过了代码。 例如,如果表达式树的前缀符号是 * 1 + 2 3 那么中序树的输出和括号应该是 (1+(2*3)) 但我得到的输出是 (1(23)+)*
public String toStringPrettyInFix(){
return printInorder(root)+")";
}
String printInorder(FCNSTreeNode root)
{
String s="";
if (root == null)
return "";
if(root.firstChild!=null) {
s=s+"("+printInorder(root.firstChild);
}
if(root.nextSibling!=null) {
s=s+printInorder(root.nextSibling)+")";
}
System.out.println(s);
return s;
}
【问题讨论】:
-
您好,欢迎来到 StackOverflow。请花一些时间阅读帮助页面,尤其是名为"What topics can I ask about here?" 和"What types of questions should I avoid asking?" 的部分。更重要的是,请阅读the Stack Overflow question checklist。您可能还想了解Minimal, Complete, and Verifiable Examples。
-
对于您的问题-您没有附加“中间元素”,这就是不考虑它的原因。在
if(root.firstChild!=null) { ... }和if(root.nextSibling!=null) { ... }之间的某个地方,您应该处理root.middleElement或其他任何名称。
标签: java tree expression inorder