解二叉树 [英] Solving Binary Tree

查看:126
本文介绍了解二叉树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人给我x作为参数时,谁能解释我如何求解表达式树?

Can anyone explain how I Solve a expression Tree when I'm given x as a parameter?

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

For example, I have the equation ((2*x)) + 4and let's say in the parameter, x = 3. This would give us 10 and the method would return this.

我考虑这样做的方式是递归执行,但由于参数必须为double x,所以我不能真正做到这一点.

The way I thought about doing this was to do it recursively but I can't really do it because the parameter has to be the double x.

有什么想法吗?

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

Here's the code I have so far.

  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 ()
    }
}

推荐答案

您不是只按以下顺序说些什么吗?

Wouldn't you just say something on the order of:

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;
}

(请自由对待您的结构,因为我不了解所有内容的全部意图.)

(Taking liberties with your structure because I don't know the full intent of everything.)

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

(I'm assuming your structure is defined to be evaluating a function of only one variable, which is why you pass in x rather than passing in a dictionary of variable values.)

这篇关于解二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆