Python codes to share, similar to Basic Calculator


  • 0
    C
    class Solution(object):
        def str2tree(self, s):
            return self.str2tree2(s, [0])
            
        def str2tree2(self, s, ind):
            """
            :type s: str
            :rtype: TreeNode
            """
            L = len(s)
            if ind[0]>=L:
                return None
            
            i, sign, node, num = ind[0], 1, None, 0
            
            while i < L:
                if s[i] == '-':
                    sign = -1
                    i += 1
                elif s[i] == '(':
                    if node is None:
                        node = TreeNode( sign*num )
                        ind[0] = i+1
                        node.left = self.str2tree2(s, ind)
                        i = ind[0]
                    else:
                        ind[0] = i+1
                        node.right = self.str2tree2(s, ind)
                        i = ind[0]
                elif s[i] == ')':
                    if node is None:
                        node = TreeNode( sign*num )
                    ind[0] = i+1
                    return node
                elif s[i].isdigit():
                    num = 10*num+int(s[i])
                    i += 1
                    
            if node is not None:
                return node
            return TreeNode( sign*num )
    

Log in to reply
 

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