a Python sollution

  • 0
    class Solution(object):
        def tree2str(self, t):
            if not t: return ''
            l = []
            self.dfs(t, l)
            return "".join(l)
        def dfs(self, root, l):
            if root:
                if root.left and root.right:
                    l.append('('); self.dfs(root.left,l); l.append(')')
                    l.append('('); self.dfs(root.right,l); l.append(')')
                if root.left and not root.right:
                    l.append('('); self.dfs(root.left, l); l.append(')')
                if root.right and not root.left:
                    l.append('('); self.dfs(root.right, l); l.append(')')

Log in to reply

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