Java Reference
In-Depth Information
private double
evaluate(BinaryNodeInterface<String> rootNode)
{
double
result;
if
(rootNode ==
null
)
result = 0;
else if
(rootNode.isLeaf())
{
String variable = rootNode.getData();
result = getValueOf(variable);
}
else
{
double
firstOperand = evaluate(rootNode.getLeftChild());
double
secondOperand = evaluate(rootNode.getRightChild());
String operator = rootNode.getData();
result = compute(operator, firstOperand, secondOperand);
}
// end if
return
result;
}
// end evaluate
private double
getValueOf(String variable)
{
. . .
}
// end getValueOf
private double
compute(String operator,
double
firstOperand,
double
secondOperand)
{
. . .
}
// end compute
}
// end ExpressionTree
The public method
evaluate
calls a private method
evaluate
that is recursive. This private
method calls the private methods
getValueOf
and
compute
as well as methods declared in
BinaryNodeInterface
. The method
getValueOf
returns the numeric value of a given variable in
the expression, and
compute
returns the result of a given arithmetic operation and two given
operands.
Notice how important the methods of the class
BinaryNode
are to the implementation of
evaluate
. For this reason, we do not want
BinaryNode
to be hidden within
BinaryTree
. Rather, it
should be part of a package.
Question 6
Trace the method
evaluate
for the expression tree in Figure 23-14c of the pre-
vious chapter. What value is returned? Assume that
a
is 3,
b
is 4, and
c
is 5.