【发布时间】:2016-02-05 11:48:10
【问题描述】:
所以我定义了一个递归函数,它将 x 的值(如算术变量 x,即“x + 3 = 5”)作为参数并返回算术表达式的结果。该表达式取自如下所示的二进制表达式树:
你从根开始,一直往下走,直到碰到树叶,一旦你回来了。那么树上的表达式是:
x * ( (x + 2) + cos(x-4) )。
我的这个函数的代码如下:
// Returns the value of the expression rooted at a given node
// when x has a certain value
double evaluate(double x) {
if (this.isLeaf()) {
//convert every instance of 'x' to the specified value
if (this.value.equals("x")) {
this.value = Double.toString(x);
}
//return the string-converted-to-double
return Double.parseDouble(this.value);
}
//if-else statements to work as the arithmetic operations from the tree. Checks the given node and performs the required operation
else {
if(this.value.equals("sin")) { return Math.sin(evaluate(Double.parseDouble(this.leftChild.value))); }
if(this.value.equals("cos")) { return Math.cos(evaluate(Double.parseDouble(this.leftChild.value))); }
if(this.value.equals("exp")) { return Math.pow(evaluate(Double.parseDouble(this.leftChild.value)), evaluate(Double.parseDouble(this.rightChild.value))); }
if(this.value.equals("*")) { return evaluate(Double.parseDouble(this.leftChild.value)) * evaluate(Double.parseDouble(this.rightChild.value)); }
if(this.value.equals("/")) { return evaluate(Double.parseDouble(this.leftChild.value)) / evaluate(Double.parseDouble(this.rightChild.value)); }
if(this.value.equals("+")) { return evaluate(Double.parseDouble(this.leftChild.value)) + evaluate(Double.parseDouble(this.rightChild.value)); }
if(this.value.equals("-")) { return evaluate(Double.parseDouble(this.leftChild.value)) - evaluate(Double.parseDouble(this.rightChild.value)); }
}
}
但是编译器抛出一个错误,告诉我我的函数必须返回一个双精度类型。 if 和 else 语句都直接返回一个 double - if 语句和 else 语句通过同一函数返回的 2 个 double 的总和。这里有什么交易?如果我在 if-else 之外放置一个 return 语句,则错误会自行解决,但要解决这个问题,我需要在每次递归中保持静态或全局变量的一致性。我想知道我的函数有什么问题,因为它感觉比全局变量更直观,而且我认为我在这里遗漏了一个关于递归的关键概念。感谢您提供任何帮助-谢谢!
【问题讨论】:
-
你需要最后一个 return 语句,以防万一没有满足那些
ifs所以试着在最后返回一个 -1
标签: java recursion return binary-tree return-type