Python straightforward with tree traversal.


  • 0
    T

    Hello, I'm new to Python. Can you help me to improve the code.
    Thanks

    class Solution(object):
        def preorder(self, t):
            if not t:
                return ""
            self.res += str(t.val)
            if t.left and t.right:
                self.res += '('
                self.preorder(t.left)
                self.res += ')'
                self.res += '('
                self.preorder(t.right)
                self.res += ')'
            elif t.left:
                self.res += '('
                self.preorder(t.left)
                self.res += ')'
            elif t.right:
                self.res += '()'
                self.res += '('
                self.preorder(t.right)
                self.res += ')'
            else:
                return self.res
    
        def tree2str(self, t):
            """
            :type t: TreeNode
            :rtype: str
            """
            self.res = ""
            self.preorder(t)
            return self.res
    

Log in to reply
 

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