python 1 line ...


  • 0

    Code like this, You need to watch out the condition left==None and right==None|right!=None|left!=None and right==None

    class Solution(object):
        def tree2str(self, t):
            """
            :type t: TreeNode
            :rtype: str
            """
            return "" if t==None else "%s" % t.val if t.left==None and t.right==None else "{0}({1})".format(t.val,self.tree2str(t.left)) if t.right==None and t.left!=None else "{0}({1})({2})".format(t.val,self.tree2str(t.left),self.tree2str(t.right))
    

  • 0

    my long 1-line ......

        return str(t.val) + ( '(' + self.tree2str(t.left) + ')' if t.left or t.right else '') + (('(' + self.tree2str(t.right) + ')') if t.right else '') if t else ''
    

Log in to reply
 

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