733. Design An Expression Tree With Evaluate Function

Implement an Expression Tree for evaluating arithmetic expressions. Each node of the tree represents either:

  • An operand (integer).
  • An operator (+, -, *, /).

You need to:

  1. Build an expression tree from a given postfix expression.
  2. Evaluate the expression tree.

Example 1:

Input: s = ["3", "4", "+", "2", "*", "7", "/"]

Output: 2

Explanation:

This expression evaluates to the above binary tree with expression ((3+4)*2)/7 = 14/7 = 2.

Example 2:

Input: s = ["4", "5", "2", "7", "+", "-", "*"]

Output: -16

Explanation:

This expression evaluates to the above binary tree with expression 4 * (5 - (2 + 7)) = 4 * (-4) = -16.

Now Your Turn!

Pick the correct output for the given input

Input: s=["5", "3", "4", "+", "5", "*"]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= s.length < 100
  • s.length is odd.
  • s consists of numbers and the characters '+', '-', '*', and '/'.
  • If s[i] is a number, its integer representation is no more than 105.
  • It is guaranteed that s is a valid expression.
  • The absolute value of the result and intermediate values will not exceed 109.
  • It is guaranteed that no expression will include division by zero.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* This is the interface for the expression tree Node.
* You should not remove it, and you can define some classes to implement it.
*/
 
class Node {
public:
virtual ~Node () {};
virtual int evaluate() const = 0;
protected:
// define your fields here
};
 
 
/**
* This is the TreeBuilder class.
* You can treat it as the driver code that takes the postinfix input
* and returns the expression tree representing it as a Node.
*/
 
class TreeBuilder {
public:
Node* buildTree(vector<string>& postfix) {
// Your Code Goes Here
}
};
 
 
/**
* Your TreeBuilder object will be instantiated and called as such:
* TreeBuilder* obj = new TreeBuilder();
* Node* expTree = obj->buildTree(postfix);
* int ans = expTree->evaluate();
*/
Test Case

Input:

S