Expression Trees Using Classes in C++ with Implementation
Prerequisite: Expression Tree
The expression tree is a binary tree in which each internal node corresponds to the operator and each leaf node corresponds to the operand so for example expression tree for 3 + ((5+9)*2) would be:
In expression trees, leaf nodes are operands and non-leaf nodes are operators. That means an expression tree is a binary tree where internal nodes are operators and leaves are operands. An expression tree consists of binary expressions. But for a unary operator, one subtree will be empty.
Construction of Expression Tree:
- The user will provide a postfix expression for which the program will construct the expression tree.
- Inorder traversal of binary tree/expression tree will provide Infix expression of the given input.
Input: A B C*+ D/ Output: A + B * C / D
Step 1: The first three symbols are operands, so create tree nodes and push pointers to them onto a stack as shown below.
Step 2: In the Next step, an operator ‘*’ will going read, so two pointers to trees are popped, a new tree is formed and a pointer to it is pushed onto the stack
Step 3: In the Next step, an operator ‘+’ will read, so two pointers to trees are popped, a new tree is formed and a pointer to it is pushed onto the stack.
Step 4: Similarly, as above cases first we push ‘D’ into the stack and then in the last step first, will read ‘/’ and then as previous step topmost element will pop out and then will be right subtree of root ‘/’ and other node will be right subtree.
Final Constructed Expression Tree is:
Below is the C++ program to implement the above approach:
The Inorder Traversal of Expression Tree: A + B * C / D