Expression Tree
Expression Tree
* + * +
e f
+ - e f
+ -
a b c d a b c d
( 4 + 2 ) * 3 = 18
5 6
1
Inorder Traversal: (A + H) / (M - Y) Inorder Traversal (cont.)
Print second
tree
+
+ *
‘/’
+ g
‘+’ ‘-’ a *
d e
Print left subtree first Print right subtree last
7 Inorder traversal yields: (a + (b * c)) + (((d * e) + f) * g)
‘/’ ‘/’
Print left subtree second Print right subtree last Print left subtree first Print right subtree second
9 10
clear
12
2
class ExprTree {
public: Each node contains two pointers
ExprTree ( ); // Constructor struct TreeNode
~ExprTree ( ); // Destructor {
void build ( ); // build tree from prefix expression InfoNode info ; // Data member
void expression ( ) const;
TreeNode* left ; // Pointer to left child
// output expression in fully parenthesized infix form
TreeNode* right ; // Pointer to right child
float evaluate ( ) const; // evaluate expression
};
void clear ( ); // clear tree
void showStructure ( ) const; // display tree
n There is a simple O(N) stack-based n Read the postfix expression one symbol at at
algorithm to convert a postfix time:
expression into an expression tree. – If the symbol is an operand, create a one-node
tree and push a pointer to it onto the stack.
n Recall we also have an algorithm to – If the symbol is an operator, pop two tree pointers
convert an infix expression into postfix, T1 and T2 from the stack, and form a new tree
whose root is the operator, and whose children
so we can also convert an infix are T1 and T2.
expression into an expression tree – Push the new tree pointer on the stack.
without difficulty (in O(N) time).
3
Example Example
ab+cde+ :
ab+ :
+ c d e
a b
a b
+
Note: These stacks are depicted horizontally. + c +
a b
a b d e
Example Example
ab+cde+* : ab+cde+**:
+
* *
a b c +
+
d e *
a b c +
d e