Short Python


  • 0

    Basically we have 5 different situations for each t, and we just return the corresponding results.

    # 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 tree2str(self, t):
            """
            :type t: TreeNode
            :rtype: str
            """
            if not t: return ""
            s, l, r = str(t.val), "(" + self.tree2str(t.left) + ")", "(" + self.tree2str(t.right) + ")"
            return s + l + r if t.left and t.right else \
                   s + l if t.left and not t.right else \
                   s + "()" + r if not t.left and t.right else s
    

Log in to reply
 

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