Lesson learnt: for any calculator problems, keep 2 stacks: 1 for operators and 1 for operands.
class Solution { stack<ExpressionTreeNode*> op; stack<ExpressionTreeNode*> data; void eval() { ExpressionTreeNode *opnode = op.top(); op.pop(); ExpressionTreeNode *data1 = data.top(); data.pop(); ExpressionTreeNode *data2 = data.top(); data.pop(); opnode->left = data2; opnode->right = data1; data.push(opnode); } public: ExpressionTreeNode* build(vector<string> &expression) { for(auto &tmp : expression) { ExpressionTreeNode *node = new ExpressionTreeNode(tmp); switch(tmp[0]) { case '(': op.push(node); break; case '+': case '-': while(!op.empty()&&op.top()->symbol[0]!='(') { eval(); } op.push(node); break; case '*': case '/': while(!op.empty()&&(op.top()->symbol[0]=='*'||op.top()->symbol[0]=='/')) { eval(); } op.push(node); break; case ')': while(op.top()->symbol[0]!='(') { eval(); } op.pop(); break; default: data.push(node); break; } } while(!op.empty()) { eval(); } if(data.empty()) return nullptr; return data.top(); } };