python one pass O(n) recursive


  • 1
    X
    class Solution(object):
        def str2tree(self, s):
            """
            :type s: str
            :rtype: TreeNode
            """
            s += ')'
            self.i = -1
            def bld():
                self.i += 1
                j = self.i
                while s[j] not in '()':
                    j += 1
                root = TreeNode( int(s[self.i:j]) ) if j > self.i else None
                self.i = j
                
                if s[self.i] == ')':
                    self.i += 1
                    return root
                    
                root.left = bld()
                if s[self.i] == '(':
                    root.right = bld()
                    
                self.i += 1
                return root
            return bld()
    

Log in to reply
 

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