#include <iostream>
#include <string>
#include <stack>
#include <cctype>
class ExpressionTree {
private:
struct Node {
std::string data;
Node* left;
Node* right;
Node(const std::string& val) : data(val), left(nullptr), right(nullptr) {}
};
Node* root;
void destroyTree(Node* node) {
if (node) {
destroyTree(node->left);
destroyTree(node->right);
delete node;
}
}
int evaluate(Node* node) const {
if (!node) return 0;
if (isdigit(node->data[0])) {
return std::stoi(node->data);
}
int leftValue = evaluate(node->left);
int rightValue = evaluate(node->right);
if (node->data == "+") return leftValue + rightValue;
if (node->data == "-") return leftValue - rightValue;
if (node->data == "*") return leftValue * rightValue;
if (node->data == "/") return leftValue / rightValue;
return 0;
}
public:
ExpressionTree() : root(nullptr) {}
~ExpressionTree() { destroyTree(root); }
void buildFromPostfix(const std::string& postfix) {
std::stack<Node*> st;
std::string token;
for (char c : postfix) {
if (c == ' ') {
if (!token.empty()) {
Node* node = new Node(token);
if (isdigit(token[0])) {
st.push(node);
} else {
node->right = st.top(); st.pop();
node->left = st.top(); st.pop();
st.push(node);
}
token.clear();
}
} else {
token += c;
}
}
if (!token.empty()) {
Node* node = new Node(token);
if (isdigit(token[0])) {
st.push(node);
} else {
node->right = st.top(); st.pop();
node->left = st.top(); st.pop();
st.push(node);
}
}
if (!st.empty()) {
root = st.top();
}
}
int evaluate() const {
return evaluate(root);
}
};
int main() {
ExpressionTree tree;
// Postfix expression: 3 4 + 2 * 7 -
// Equivalent infix: ((3 + 4) * 2) - 7
tree.buildFromPostfix("3 4 + 2 * 7 -");
std::cout << "Expression evaluation result: " << tree.evaluate() << std::endl;
return 0;
}