Recursive Method (Java)?
I am asked to write a recursive method named evaluate which computes the value of any non-null expression tree.
I am given the following class:
public class ExpTN {
public String op; // stores "+","-","*","/", or "value"
public int value; // significant only if op is "value"
public ExpTN left, right; // significant only if op ISN'T a value;
Below is generally what I was thinking of doing.
Am I on the right path? Any ideas/suggestions or other ways of writing such a method?
Thank you! =)
--------------
static double evaluate( ExpNode node ) {
if ( node.kind == NUMBER ) {
// The value of a NUMBER node is the # it holds.
return node.number; }
else {
double leftVal = getValue( node.left );
double rightVal = getValue( node.right );
switch ( node.op ) {
case '+': return leftVal + rightVal;
case '-': return leftVal - rightVal;
case '*': return leftVal * rightVal;
case '/': return leftVal / rightVal;
default: return Double.NaN;
} } }
Would the complexity class of that be O(N)?
|