7 Line Simplest C++ Recursive Solution, very very understandable


  • 0
    H

    If num, return it
    else do operation

    int evalRPN(vector<string>& tokens) {
            string s = tokens.back(); tokens.pop_back();
            if(s != "+" && s != "-" && s != "*" && s != "/") return stoi(s);
            
            int r2 = evalRPN(tokens), r1 = evalRPN(tokens);
            
            if(s == "+") return r1 + r2;
            if(s == "-") return r1 - r2;
            if(s == "*") return r1 * r2;
            if(s == "/") return r1 / r2;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.