My python solution, recursion


  • 0
    G
    def tree2str(self, root):
            """
            :type t: TreeNode
            :rtype: str
            """
            if not root:
                return ''
            elif not root.left and not root.right:
                return str(root.val)
            elif root.left and not root.right:
                return str(root.val) + '(' + self.tree2str(root.left) + ')'
            else:
                return str(root.val) + '(' + self.tree2str(root.left) + ')' + '(' + self.tree2str(root.right) + ')'
    

Log in to reply
 

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