将括号添加到表达式树

时间:2017-03-09 12:46:03

标签: java binary-tree expression-trees

我正在尝试编写一个给定树的函数,创建一个中缀表达式,只需要必要的括号。例如,如果表达式((a-3) - (b-5))已输入树中,则此函数将返回字符串a-3-(b-5)或((a-3) (b-5))返回(a-3)(b-5)[由于某种原因,它们不会在这些表达式之间显示*]。我目前有一个函数将整个表达式括在括号中,对于它返回的第一个例子(a-3-b-5)。有人可以解释导致它的原因a)不为每个单独的表达式添加括号,以及b)如何修改它以仅添加必需的括号。

编辑:略微修改,以便每个表达式现在都有括号但不是整个表达式。现在生成(a-3) - (b-5)作为输出。

private String inorder(ExpTree t) {
    if (t != null) {
        //if node and left child are operators
        if (t.type == 2) {
            if (getPri(t) <= getPri(parent) && t != parent) {
                strBuf.append('(');
            }
        }
        inorder(t.lChild, t);
        strBuf.append(t.leafVal);
        inorder(t.rChild, t);
        //if node and right child are operators
        if (t.type == 2) {
            if (getPri(t) <= getPri(parent) && t != parent) {
                strBuf.append(')');
            }
        }
    }
    return strBuf.toString();

private int getPri(ExpTree t) {
    String leaf = "";
    if (t.type == 2) {
        leaf = t.leafVal.toString();
    }
    else {
        return 0;
    }
    if (leaf == "*" || leaf == "%" || leaf == "/") {
        return 2;
    }
    else if (leaf == "+" || leaf == "-") {
        return 1;
    }
    return 0;
}

ExpTree类

public class ExpTree {
private int type;
private Object leafVal;
private ExpTree lChild, rChild;
public static final int NUM = 0, VAL = 1, OP = 2;

public ExpTree(int type, Object leafVal, ExpTree l, ExpTree r) {
    this.type = type;
    this.leafVal = leafVal;
    this.lChild = l;
    this.rChild = r;
}

0 个答案:

没有答案