【问题标题】:Inorder traversal of expression tree in javajava中表达式树的中序遍历
【发布时间】: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;

}

【问题讨论】:

标签: java tree expression inorder


【解决方案1】:

按顺序向左走中间再向右走。这里你错过了中间部分

if(root.firstChild!=null) {


    s=s+"("+printInorder(root.firstChild);

}     

s = s+root.value //value is whatever stored in node 

if(root.nextSibling!=null) {
    s=s+printInorder(root.nextSibling)+")";

}

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 2015-09-11
    • 2010-09-08
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多