解二叉树

时间:2011-11-29 04:30:59

标签: java expression-trees

当我将x作为参数时,有人可以解释我如何解决表达式树吗?

例如,我有等式((2 * x))+ 4,让我们在参数x = 3中说。 这将给我们10,该方法将返回此。

我想这样做的方法是递归地做,但我不能真正做到这一点,因为参数必须是双x。

有什么想法吗?

这是我到目前为止的代码。

  public double evaluate(double x) throws ExpressionTreeNodeException {
    ExpressionTreeNode n = new ExpressionTreeNode();
    n.setValue(getValue());
    n.setType(getType());
    if ( n.getRightChild() == null && n.getLeftChild() == null){
        double RootLeaf = Double.parseDouble(n.getValue());
        return RootLeaf;
    } else {
        double operand1 = 
        return ()
    }
}

1 个答案:

答案 0 :(得分:1)

你不会只是按照以下顺序说些什么:

if ( n.getRightChild() == null && n.getLeftChild() == null){
    double RootLeaf = Double.parseDouble(n.getValue());
    return RootLeaf;
} else if (n.getLeftChild() == null) {
    // Evaluate prefix operator -- assume no postfix operators
    double operand1 = n.getRightChild().evaluate(x);
    double result = n.getType().evaluateMonadic(operand1);
    return result;
} else {
    // Evaluate diadic operator
    double operand1 = n.getLeftChild().evaluate(x);
    double operand2 = n.getRightChild().evaluate(x);
    double result = n.getType().evaluateDiadic(operand1, operand2);
    return result;
}

(对你的结构采取自由,因为我不知道一切的全部意图。)

(我假设您的结构被定义为仅评估一个变量的函数,这就是您传入x而不是传入变量值字典的原因。)