<p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>

<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;1 + 1&quot;
<strong>Output:</strong> 2
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot; 2-1 + 2 &quot;
<strong>Output:</strong> 3
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot;
<strong>Output:</strong> 23
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>
	<li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li>
	<li><code>s</code> represents a valid expression.</li>
	<li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li>
	<li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</code> is valid).</li>
	<li>There will be no two consecutive operators in the input.</li>
	<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>

import ast
import re
import sys
sys.setrecursionlimit(100000)

class ExprNode:
    def __init__(self, child1, child2):
        self.children = [child1, child2]
    def __str__(self):
        return("Expression")

class TermNode:
    def __init__(self, op, child1, child2):
        self.children = [child1, child2]
        self.op = op
    def __str__(self):
        if self.op == "+":
            return("Term PLUS")
        else:
            return("Term MINUS")

class BaseNode:
    def __init__(self, child, val=None):
        self.children = [child]
        self.val = val
    def __str__(self):
        if self.val == None:
            return("Parenthesis")
        else:
            return("Number " + str(self.val))

class Parser:
    def __init__(self, tokens):
        self.tokens = tokens
        self.cur = 0
    def expr(self):
        curtoken = self.tokens[self.cur]
        if curtoken.isdigit():
            self.cur += 1
            node = self.term()
            if not node:
                return BaseNode(None, int(curtoken))
            else:
                return ExprNode(BaseNode(None, int(curtoken)), node)
        else:
            # left parenthesis case
            b_node = self.base()
            t_node = self.term()
            return ExprNode(b_node, t_node)
    def term(self):
        if self.cur >= len(self.tokens) - 1:
            return None
        curtoken = self.tokens[self.cur]
        if curtoken in ["+", "-"]:
            self.cur += 1
            nexttoken = self.tokens[self.cur]
            if nexttoken.isdigit():
                self.cur += 1
                node = self.term()
                return TermNode(curtoken, BaseNode(None, int(nexttoken)), node)
            else:
                b_node = self.base()
                t_node = self.term()
                return TermNode(curtoken, b_node, t_node)
        else:
            return None

    # parses the parenthesis case only
    def base(self):
        if self.tokens[self.cur] == "(":
            self.cur += 1
            node = self.expr()
            if self.tokens[self.cur] != ")":
                print("Syntax Error: No matching right parenthesis")
                return None
            self.cur += 1
            return BaseNode(node)

class Solution:
    def calculate(self, s: str) -> int:
        def lexer(s):
            expression = re.sub(r'\s+', "", s)
            expression = re.findall(r'\d+|[\(\)+-]', expression)
            formatted = []
            for e in expression:
                if e == "-" and (not formatted or formatted[-1] == "("):
                    formatted.append("0")
                formatted.append(e)
            return formatted
        def print_nodes(n, lvl=0):
            if not n:
                return
            print(" " * lvl, end="")
            print("|", end="")
            print("--" * lvl, end="")
            print(n)
            
            for c in n.children:
                print_nodes(c, lvl+1)
            
        rpn = []
        def emit_rpn(n):
            if not n:
                return
            if type(n) == TermNode:
                if n.children[0].val != None:
                    rpn.append(n.children[0].val)
                    rpn.append(n.op)
                else:
                    emit_rpn(n.children[0])
                    rpn.append(n.op)
                emit_rpn(n.children[1])


            elif type(n) == BaseNode:
                if n.val != None:
                    rpn.append(n.val)
                else:
                    emit_rpn(n.children[0])

            else:
                emit_rpn(n.children[0])
                emit_rpn(n.children[1])
        
        def evaluate_rpn(rpns):
            stack = []
            for token in rpns :
                if token == '+' :
                    a , b = stack.pop() , stack.pop()
                    stack.append( a + b ) 
                elif token == '-':
                    a , b = stack.pop() , stack.pop()
                    stack.append( b - a ) 
                else:
                    stack.append(token) 
            return stack.pop()                 
        
        ps = Parser(lexer(s))
        res = ps.expr()
        emit_rpn(res)
        return evaluate_rpn(rpn)
46636