Monday, August 25, 2014

Arithmetic expression tree and Evaluate Reverse Polish Notation

There's a problem called
Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

The problem becomes simple if we know the rule of using a stack to evaluate the reverse polish notation (RPN).
1. Push every numbers in to the stack
2. When an operand occurs, pop the first 2 numbers out of the stack and calculate c=(a operand b)
3. Push c into the stack



    int evalRPN(vector<string> &tokens) {
       
        int n = tokens.size();
       
        stack<int> numbers;
        string op ="+-*/";
       
        for (int i=0; i<n; i++)
        {
            int j=0;
            int t = op.find(tokens[i]);
           
            if (t!=-1)
            {
                int a = numbers.top();
                numbers.pop();
                int b = numbers.top();
                numbers.pop();
               
                switch(t){
                case 0 :
                j = a+b;
                break;
                case 1:
                j = b-a;
                break;
                case 2:
                j = a*b;
                break;
                case 3:
                j = b/a;
                break;
                }
                numbers.push(j);
            }
            else
            {
                j = atoi(tokens[i].c_str());
                numbers.push(j);
            }
           
        }
       
        return numbers.top();
    }

Even shorter version without many APIs

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
       stack<int> numStack;
       for(int tokI = 0; tokI < tokens.size(); ++ tokI)
           if(tokens[tokI] == "*" || tokens[tokI] == "+" || tokens[tokI] ==
"/" || tokens[tokI] == "-")
           {
              int val1 = numStack.top(); numStack.pop();
              int val2 = numStack.top(), res; numStack.pop();
              if(tokens[tokI] == "+")
                  res = val1 + val2;
              else if(tokens[tokI] == "*")
                  res = val1 * val2;
              else if(tokens[tokI] == "-")
                  res = val2 - val1;
              else
                  res = val2 / val1;
              numStack.push(res);
           }
           else
              numStack.push(atoi(tokens[tokI].c_str()));
       return numStack.top();
    }
};


Related problems can also be solved with info from these sources

http://fredosaurus.com/notes-cpp/ds-trees/10exptrees.html

http://penguin.ewu.edu/cscd300/Topic/ExpressionTree/index.html

http://nova.umuc.edu/~duchon/exTrees/

No comments:

Post a Comment