TreeNode
class.
TreeNode(Object value) -- Create a new tree.
void setChild(int childnum, TreeNode child) --
Set a child (subtree) of the current tree.
TreeNode getChild(int childnum) -- Get one of the subtrees
of the current tree.
Object value() -- Get the value at the root of the tree.
+ in 2+3*5.
2+3*5 has
+ at the root,
2 as the left subtree,
* as the root of the right subtree,
3 as the left subtree of the right subtree,
and
5 as the right subtree of the right subtree.
+ / \ 2 * / \ 3 5
ExpressionTree two = new ExpressionTree(2); ExpressionTree three = new ExpressionTree(3); ExpressionTree five = new ExpressionTree(5); ExpressionTree right = new ExpressionTree(Operation.MULTIPLY, three, five); ExpressionTree whole = new ExpressionTree(Operation.ADD, two, right);
ExpressionTree whole = new ExpressionTree(); whole.setRoot(Operation.ADD); whole.setChild(0, two); whole.setChild(1, right);
/** Get the evaluate of the current expression. */
public int evaluate() throws Exception {
if (type == INTEGER) {
return ((Integer) getRoot()).intValue();
} // INTEGER
else if (type == VARIABLE) {
return lookupVariable(getRoot());
} // VARIABLE
else if (type == OPERATION) {
// Evaluate arguments
int[] args = new int(arity());
for (int i = 0; i < arity(); ++i) {
args[i] = getChild(i).evaluate();
} // for
// Apply the operation
return ((Operation) getRoot()).apply(args);
} // OPERATION
else {
throw new Exception("Invalid expression tree");
}
} // evaluate()
Operation
class which supports an apply(int[]) method. That method
might look something like:
public int apply(int[] args) throws MathException {
if (op == ADD) {
if (args.length != 2) {
throw new MathException("Add requires two arguments");
}
return args[0] + args[1];
}
else if (op == MULTIPLY) {
if (args.length != 2) {
throw new MathException("Multiply requires two arguments");
}
return args[0] * args[1];
}
else if (op == NEGATE) {
if (args.length != 1) {
throw new MathException("Negation requires one argument");
}
return -args[0];
}
...
} // apply
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
Source text last modified Wed Nov 12 12:18:48 1997.
This page generated on Wed Nov 12 12:20:30 1997 by SiteWeaver.
Contact our webmaster at rebelsky@math.grin.edu