小编Jus*_*tin的帖子

如何使用二进制抽象语法树来生成具有最小正确括号的中缀表示法

我正在传递一个表示数学公式的二进制AST.每个内部节点都是运算符,叶节点是操作数.我需要走树并以中缀表示法输出公式.通过使用递归算法(例如Print()下面显示的方法)遍历树,这很容易实现.该Print()方法的问题在于转换为中缀时操作顺序丢失,因为没有生成括号.

我编写了PrintWithParens()输出正确的中缀公式的方法,但它添加了无关的括号.您可以在我的main方法的四个案例中的三个中看到它在没有必要时添加括号.

我一直绞尽脑汁试图弄清楚PrintWithMinimalParens()应该是什么样的正确算法.我确信必须有一个算法只能在必要时输出括号来组合术语,但是我无法正确实现它.我想我必须要查看当前节点下面树中运算符的优先级,但我现在的算法不起作用(参见我的main方法中的最后两种情况.不需要括号,但是我的逻辑添加它们).

public class Test {

static abstract class Node {

    Node left;
    Node right;
    String text;

    abstract void Print();
    abstract void PrintWithParens();
    abstract void PrintWithMinimalParens();

    int precedence()
    {
        return 0;
    }
}

enum Operator { 
    PLUS(1,"+"), 
    MINUS(1, "-"), 
    MULTIPLY(2, "*"), 
    DIVIDE(2, "/"), 
    POW(3, "^") 
    ;

    private final int precedence;
    private final String text;

    private Operator(int precedence, String text)
    {
        this.precedence = precedence;
        this.text = text;
    }

    @Override
    public String toString() …
Run Code Online (Sandbox Code Playgroud)

algorithm binary-tree

5
推荐指数
1
解决办法
1623
查看次数

标签 统计

algorithm ×1

binary-tree ×1