Solving Binary Tree

有些话、适合烂在心里 提交于 2019-12-25 08:49:40

问题


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

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.

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.

Any thoughts?

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

回答1:


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.)

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



来源:https://stackoverflow.com/questions/8305878/solving-binary-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!