Expression Trees
Binary tree traversal useful for arithmetic expression evaluation
- Internal nodes contain operators
- Leaf nodes contain numbers or variables
Widely used in compiler construction (optimization phase)
Binary operator has two subtrees, unary operator has only one (left or right may be important; consider ++ operator)
Semantics: the value of an expression can be found by a variant of postorder traversal:
- The value of a leaf node is the value of the number or variable contained in the leaf
- The value of an internal node is found by recursively finding the values of the left and right subtrees, and then applying the operator contained in the node to these values
Note that tree structure specifies unambiguous operation order
Build trees and traverse in all orders: x=a-(b*c), x=(a-b)*c, y=a*x?3+b*x?2+c*x+d Which traversal order(s) are useful?