python - tree2str


  • 0
    S
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def preorder(self, t):
            
            ans = ''
            if not t:
                return ans
            else:
                ans += str(t.val)
                ans += '(' + self.preorder(t.left) + ')'
                ans += '(' + self.preorder(t.right) + ')'
                
            # eliminate trailing ()
            revans = ans[::-1]
            idx = 0
            for i,c in enumerate(revans):
                if revans[i] == ')':
                    if revans[i+1] == '(':
                        idx += 2
                    else:
                        break
            
            revans = revans[idx:]
            ans = revans[::-1]
            
            return ans
        
        def tree2str(self, t):
            """
            :type t: TreeNode
            :rtype: str
            """
            ans = ''
            if not t:
                return ans
            
            ans += self.preorder(t)
            return ans
                
    

Log in to reply
 

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