COP 3503 – Computer Science II
–
CLASS NOTES

DAY #18
Expression Trees
Expression trees are a useful technique for representing and evaluating
expressions.
The leaves of an expression tree represent the operands of the
expression which may be either constants or variables.
The internal nodes
represent the operations embedded in the expression.
Most operations are binary
operations and thus most internal nodes will have two children, however, this is not
always the case.
Unary operators, such as unary minus, will have only a single
child node representing the single operand of such an operator.
Other operations
may be tertiary, quadary, etc. and such operation nodes will have three or more
child nodes.
An expression tree
T
is evaluated by applying the operator in the root
node to values obtained through recursive evaluation of the left and right subtrees.
Shown below is an expression tree which represents the expression (a+b)*(c

d):
Evaluation of the expression tree shown above produced the expression:
((a+b)*(c

d)).
Note that this is an overly parenthesized infix expression as a result
of the recursive production of a parenthesized left subexpression followed by the
operator in the root node followed by a recursively generated parenthesized right
subexpression.
The traversal of the tree that produced this expression is called an
inorder traversal
and occurred by recursively traversing the left subtree followed
by the root followed by the right subtree.
Day 18 
1
*
+

a
b
c
d
Tree Traversal to Produce Infix Expressions
Recursively produce the left subexpression.
Print out the root node.
Recursively produce the right subexpression.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentSpecific Traversal Algorithms to Convert Expressions
The following algorithms convert infix expressions to either prefix or postfix
expressions.
A preorder expression tree traversal generates a preorder expression if the
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '08
 Staff
 Computer Science

Click to edit the document details