Expression tree

advertisement
EXAMPLE: Expression tree
An expression tree is a tree whose leaves contain the operands of the expression,
and the other nodes contain the operators.
Consider the expression:
(a + b*c) * ( d + e)
It can be represented as a binary tree:
*
+
+
a
*
b
d
e
c
In-order traversal - (left subtree_root right)
reconstructs the expression: (a + b*c) * ( d + e)
Post-order traversal - results in the corresponding postfix expression:
abc*+de+*
1
How to construct a postfix expression using a stack:
While there are symbols in the expression do:
Read a symbol sym.
If (sym = operand) print it
If (sym = '(' )
push(S, sym)
If (sym = operation)
If (stack is empty) push(S, sym)
Else temp_sym = pop(S)
If temp_sym higher or equal priority
print temp_sym
push(sym)
Else push(temp_sym)
push(sym)
If (sym = ')' )
pop and print until '(' is encountered, do not print '('.
Pop and print the remaining symbols from the stack.
Given a postfix expression, we can construct the expression tree, using a stack that
contains pointers to the tree nodes
Constructing an expression tree
The expression tree can be built using the postfix expression. We read the postfix expression one
symbol at a time. If the symbol is an operand, we create a one-node tree and push a pointer to it
into a stack. If the symbol is an operator, we pop twice pointers to two trees T1 and T2 (T1 is
popped first) and form a new tree whose root is the operator and whose left and right children are
T2 and T1, respectively. A pointer to this new tree is then pushed onto the stack.
Example: Consider the expression (a + b) * (c * (d + e)). The postfix expression is:
ab+cde+**
The first tow symbols are operands, so we create one-node trees and push pointers to them onto a
stack (for convenience, we will have the stack grow from left to right in the diagrams.)
a
b
Next, we read '+' so two pointers to trees are popped, a new tree is formed, and a pointer to it is
pushed onto the stack:
2
+
a
b
Next, c, d, and e are read, and for each a one-node tree is created and a pointer to the
corresponding tree is pushed onto the stack:
+
c
a
d
e
b
Then we read ' + ' and two trees are merged:
+
c
a
+
b
d
e
Then, ' * ' is read, so we pop two tree pointers and form a new tree with '*' as root :
3
+
*
a
b
+
c
d
e
Finally, the last symbol '*' is read, two trees are merged, and a pointer to the final tree is pushed
onto the stack:
*
*
+
a
b
+
c
d
e
4
Download