问题
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