Evaluate Reverse Polish Notation


逆波兰式就是二叉树树后根遍历的结果,逆波兰式在借助栈进行算式运算的时候一个很好的优势就是不用比较栈顶操作符的优先级,操作过程很简单:

1)若是操作数,入栈

2)若是操作符,就像扁担挑水一样,在栈里挑出两个数进行运算(注意第一操作数和第二操作数),将结果作为操作数再次压入栈中,重复操作,直到表达式末尾。

//["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
/*                              +
                                |
                              /   \
                             4      /
                                    |
                                  /   \
                                 13    5
LRD: 4, 13, 5, /, +

操作过程:

  while(notation has more item)
   if notation[i] is a digital, s.push(notation[i])
   if notation[i] is an operator:
    op1 = s.top(),s.pop() op2 = s.top(),s.pop()
    re = op2 notation[i] op1.
	     s.push(re)
  return s.top() 

//code

class Solution {
public:
	
	int evalRPN(vector<string> &tokens) {
		stack<int> s_numbers;
		vector<string>::iterator sit = tokens.begin();
		while (sit != tokens.end())
		{
          if(IsOperator(*sit))
		  {
			 int op2 = s_numbers.top();
			 s_numbers.pop();
			 int op1 = s_numbers.top();
			 s_numbers.pop();
			 if(*sit == "+")  
				 s_numbers.push(op1 + op2);
			 else if(*sit == "-")  
				 s_numbers.push(op1 - op2);
			 else if(*sit == "*")  
				 s_numbers.push(op1 * op2);
			 else     
				 s_numbers.push(op1 / op2);

		  }
		  else
			  s_numbers.push(stoi(*sit));	
		  ++sit;
		}
		return s_numbers.top();
	}
	bool IsOperator(string s)
	{
		return (s == "+" || s == "-" || s == "*" || s == "/");
	}
};


你可能感兴趣的:(LeetCode,Algorithm,tree,栈,逆波兰式)