Python, Straightforward with Explanation


  • 14

    We do this recursively.

    • If the tree is empty, we return an empty string.
    • We record each child as '(' + (string of child) + ')'
    • If there is a right child but no left child, we still need to record '()' instead of empty string.
    def tree2str(self, t):
        if not t: return ''
        left = '({})'.format(self.tree2str(t.left)) if (t.left or t.right) else ''
        right = '({})'.format(self.tree2str(t.right)) if t.right else ''
        return '{}{}{}'.format(t.val, left, right)
    

Log in to reply
 

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