从表达式树打印出后序表达式的问题。 (JAVA)

时间:2014-04-23 03:11:01

标签: java parsing tree

这是我的代码。但是,每当我输入诸如“2 * 3 + 6/3”之类的表达式时,它会将输出打印为“36/3 + 2 *”,这不是正确的后缀格式。有人在我的代码中看到任何错误吗?非常感谢!

package expressiontree;
import java.util.LinkedList;
import java.util.List;

class Stack
{
    private List stack = new LinkedList();

    public void push(TreeNode node)
    {
        stack.add(node);
    }

    public TreeNode pop()
    {
        int top = stack.size()-1;
        if (top < 0) return null;
        TreeNode node = (TreeNode)stack.get(top);
        stack.remove(top);
        return node;
    }
}

class TreeNode
{
    TreeNode left;
    TreeNode right;
    char data;

    TreeNode(){}

    TreeNode(char c)
    {
        this.data = c;
    }
}

public class ExpressionTree {

    String expression;
    TreeNode tree;
    Stack operandstack = new Stack();
    Stack operatorstack = new Stack();

    private boolean isOperator(char c)
    {
        String operator = "+-*/";
        if(operator.indexOf(c)==-1)
        return false;

        return true;
    }

    // parses an expression and creates two stacks
    private void parseExpression(String exp)
    {
        for(int i=0; i < exp.length(); i++) {
            char c = exp.charAt(i);
            if(isOperator(c))
            operatorstack.push(new TreeNode(c));
            else{
                operandstack.push(new TreeNode(c));
            }
        }
    }

    private TreeNode create_tree()
    {
        TreeNode node = new TreeNode();
        while((node = operatorstack.pop())!=null)
        {
            TreeNode oper1 = operandstack.pop();
            TreeNode oper2 = operandstack.pop();

            TreeNode exp = create_expression(oper1, node, oper2);
            operandstack.push(exp);
        }

        return operandstack.pop();
    }

    private TreeNode create_expression(TreeNode oper1, TreeNode operator, TreeNode oper2)
    {
        TreeNode expression = new TreeNode(operator.data);
        expression.left = oper1;
        expression.right = oper2;

        return expression;
    }

    public static void postfix(TreeNode tn){
        if (tn == null){
            return;
        }
        else{
            postfix(tn.left);
            postfix(tn.right);  
            System.out.print(tn.data);
        }
    }

    public static void main(String[] args)
    {
        ExpressionTree et = new ExpressionTree();
        String expression = "2*3+6/3";
        et.parseExpression(expression);
        TreeNode tn = et.create_tree();
        postfix(tn);
        System.out.println();
    }
}

1 个答案:

答案 0 :(得分:1)

我可以看到代码的两个基本问题。

1)在parseExpression中,操作数和运算符被盲目地推入各自的堆栈中。您需要注意运算符优先级(即*和/的优先级高于+ - )。为了处理运算符优先级,基本上当您看到优先级低于或等于当前运算符堆栈的运算符时,必须先评估堆栈中当前的内容,然后再将操作符推入堆栈。

2)在create_tree中,从堆栈中分配第一个和第二个操作数的代码使用第一个pop作为第一个操作数,第二个pop作为第二个操作数。它应该是相反的方式(即第一个pop是第二个操作数,第二个pop是第一个操作数)

尝试这些更改,看看它是否能解决您的问题。