example2_math_evaluation.cpp

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
#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;
}
Back to binary_tree