Python, Straightforward with Explanation


  • 19

    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)
    

  • 0
    H

    @awice Inspired by your solution, I just modify your code and I think this one is more readable. Thanks
    def tree2str(self, t):
    if not t: return ''
    left, right = '', ''
    if t.left or t.right:
    left = '({})'.format(self.tree2str(t.left))
    if(t.right):
    right = '({})'.format(self.tree2str(t.right))
    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.