【发布时间】:2017-10-16 10:30:15
【问题描述】:
我应该使用表达式树来评估后缀表达式。 编译程序时出错
"没有为 ExpressionTree.Node 类型定义方法 getElement()"
getElement 是否不适用于堆栈类? 如果不是,我应该使用什么来获取堆栈中的元素?
import java.util.Stack;
public class ExpressionTree
{
Node root;
// Node sub-class
public class Node
{
private String key; // key
private Node left; // links to subtrees
private Node right;
public Node(String key)
{
this.key = key;
}
}
// constructor to build a tree with postFix expression
public ExpressionTree(String postFixExpression)
{
Stack<Node> stack = new Stack<Node>();
String[] tokens = postFixExpression.split(" ");
for (String token: tokens)
{
if (isOperator(token))
{
Node right = stack.pop();
Node left = stack.pop();
Node node = new Node(token);
node.left = left;
node.right = right;
stack.push(node);
}
else
{
stack.push(new Node(token));
}
}
root = stack.pop();
}
private boolean isOperator(String token)
{
boolean result = false;
switch(token)
{
case "+":
case "-":
case "*":
case "/":
result = true;
break;
default:
result = false;
}
return result;
}
/**
* @return result of the expression
* @throws Exception
*/
public double evaluate() throws Exception
{
if (root==null)
result = 0;
else
{
temp = (ExpressionTreeOp)root.getElement();
if (temp.isOperator())
{
operand1 = evaluateNode(root.getLeft());
operand2 = evaluateNode(root.getRight());
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
else if (operator == '*')
result = operand1 * operand2;
else
result = operand1 / operand2;
}
else
result = temp.getValue();
}
return result;
}
}
【问题讨论】:
-
请确保您的代码是正确的。您的问题是already edited once,请检查编辑并尝试使您的代码更易于阅读。
-
你可能想用
root.getKey()替换root.getElement()
标签: java data-structures stack expression-trees