/** This traversal specializes EulerTour to compute the value of the
* expression represented by an arithmetic expression tree. It
* assumes that the elements stored at the external nodes are of type
* Integer and the elements stored at the internal nodes are of type
* OperatorInfo, with method operation(Integer x, Integer y), which
* returns the result of applying an arithmetic operation. */
public class EvaluateExpressionTour extends EulerTour {
public Object execute(BinaryTree T) {
init(T); // calls method of superclass
System.out.print("Value of the expression: ");
System.out.println(eulerTour(tree.root()));
return null; // nothing interesting to return
}
protected void visitRight(Position v, TraversalResult r) {
if (tree.isExternal(v)) r.out = v.element();
else {
OperatorInfo op = (OperatorInfo) v.element();
r.out = op.operation((Integer) r.left, (Integer) r.right);
}
}
}