Problem Description
Build a binary expression tree from the given postfix tokens where each number is a leaf and each operator is an internal node. The tree must support an evaluate function that computes the result of the represented expression.
Key Insights
- Use a stack to build the tree from postfix notation.
- When a number is encountered, create a leaf node; when an operator is encountered, pop two nodes as its children.
- The evaluate function works recursively: if the node is an operator, evaluate its left and right subtrees and then apply the operation.
- For a modular design, store operator functionality in a mapping so that additional operators can be added without modifying evaluate logic.
Space and Time Complexity
Time Complexity: O(n), where n is the number of tokens, since each token is processed once.
Space Complexity: O(n) for storing nodes in the stack and recursion stack for tree evaluation.
Solution
The algorithm processes the postfix tokens one by one using a stack. For each token:
- If it is an operand (number), create a node representing a number and push it onto the stack.
- If it is an operator, pop the top two nodes from the stack (right operand first, then left) and create a new operator node having these nodes as children. Then push the new node onto the stack. After processing all tokens, the stack contains the root of the expression tree.
The evaluate function is implemented recursively. For a leaf node, it returns the number value directly. For an operator node, it retrieves and applies the operator function (from a mapping), which ensures the design is modular and can be extended to new operators without changes to this function.