#include <iostream>
#include <stack>
#include <string>
using namespace std;
// 1. Structure for a Binary Tree Node
struct Node {
char value;
Node *left;
Node *right;
// Constructor to initialize a new node
Node(char val) {
value = val;
left = right = nullptr;
}
};
// 2. Helper function to check if a character is an operator
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
// 3. Function to construct an Expression Tree from a Postfix string
Node *constructTree(string postfix) {
stack<Node *> st;
Node *t, *t1, *t2;
// Traverse through every character of the postfix expression
for (int i = 0; i < postfix.length(); i++) {
// If the character is an OPERAND, create a node and push to Stack:
if (!isOperator(postfix[i])) {
t = new Node(postfix[i]);
st.push(t);
}
// If the character is an OPERATOR:
else {
t = new Node(postfix[i]);
// Pop the top two nodes from the stack to serve as children
// The first popped node becomes the RIGHT child (due to LIFO property)
t1 = st.top();
st.pop();
// The second popped node becomes the LEFT child
t2 = st.top();
st.pop();
// Assign children to the operator node
t->right = t1;
t->left = t2;
// Push the operator node (now a sub-tree) back onto the stack
st.push(t);
}
}
// The final remaining node in the stack is the Root of the entire tree
t = st.top();
st.pop();
return t;
}
// 4. Function for Inorder Traversal (Left - Root - Right) to print the Infix
// expression
void inorder(Node *t) {
if (t != nullptr) {
inorder(t->left);
cout << t->value << " ";
inorder(t->right);
}
}
int main() {
// Equivalent expression: (A + B) - (E * F * G)
string postfix = "AB+EF*G*-";
cout << "Input Postfix string: " << postfix << endl;
// Build the tree
Node *root = constructTree(postfix);
// Traverse the tree to verify the result
cout << "Infix expression (Inorder Traversal): ";
inorder(root);
cout << endl;
return 0;
}