解决二叉树
任何人都可以解释我是如何解决一个表达式树,当我给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()
}
}
难道你刚才说的顺序的东西:
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
而不是传递变量值的字典。)
你能解释一下evaluateMonadic(double)的作用吗? 它不起作用,因为getType()返回一个int –
我假设“type”将是运算符的类型,并且“evaluateMonadic”将评估该运算符。也可以是'evaluateMonadic(n.getType(),operand1)'或其他。当然,'evaluateDiadic'会类似,但是对于一个二元操作符来说。 –
有没有其他方法可以在不使用Monadics的情况下做到这一点?我不确定如何使用它们。 –
为什么不能你使用这个递归? – Woot4Moo
你能不能解释一下怎么递归地做呢?如果我想这样做,我想我需要参数作为根,这样我才能继续通过树。 –