Binary Expression Trees
Binary Expression Trees
-
8 5 4 +
2
3
Operations at higher levels of the tree are evaluated later than those below them. The operation at the root is always the last operation performed.
+ 4
- 8 5 4
Infix: Prefix: Postfix: ((8-5)*((4+2)/3)) *-85 /+423 85- 42+3/*
3 2
Inorder Traversal: (A + H) / (M - Y)
tree / Print second
+
A H M
- Y
Preorder Traversal: / + A H - M Y
tree / Print first
+
A H M
- Y
Postorder Traversal: A H + M Y - /
tree / Print last
+
A H M
- Y
class ExprTree
ExprTree
*
private:
TreeNode* root;
~ExprTree
Build Evaluate . . .
+ 4
10
NULL . left
OPERAND
. whichType
7
. operand
6000 . right
11
. info
// ANONYMOUS union
operation ; operand ;
OPERATOR
. whichType
+
. operation
OPERAND
. whichType
7
12
. operand
Insert new nodes, each time moving to the left until an operand has been inserted. Backtrack to the last operator, and put the next node to its right. Continue in the same pattern.
14