Java 向表达式树添加括号

Java 向表达式树添加括号,java,binary-tree,expression-trees,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))已输入到树中,则此函数将返回字符串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;
}
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;
}