C++ Notes: Expression Tree Struct
This code is a typical non-OOP solution to the expression
tree problem.
//======================================= ExprNode
struct ExprNode {
char op; // one of +, -, *, /, #
int value; // integer value
ExprNode* left; // left subtree
ExprNode* right; // right subtree
};
//======================================= eval
int eval(ExprNode* x) {
// Recursively evaluate expression tree
// and return result.
int result;
switch (x->op) {
case '+': result = eval(x->left) + eval(x->right);
break;
case '-': result = eval(x->left) - eval(x->right);
break;
// . . .
case '#': result = x->value; // an integer constant
}
return result;
}
Solutions like this are quite adequate, however the idea of
OOP programming is to bundle the constructors and methods with
the data structure as shown in the next example.