Short Python/Java with post-processing


  • 0

    I first build the string with all parentheses and then remove the unwanted ones.

    def tree2str(self, t):
        def s(t):
            return '(%d%s%s)' % (t.val, s(t.left), s(t.right)) if t else '()'
        return re.sub('(\(\))+\)', ')', s(t))[1:-1]
    

    Slight alternative:

    def tree2str(self, t):
        def s(t):
            return '%d(%s)(%s)' % (t.val, s(t.left), s(t.right)) if t else ''
        return re.sub('(\(\))+(\)|$)', r'\2', s(t))
    

    A oneliner, though here I remove the parentheses on the fly instead of at the very end:

    def tree2str(self, t):
        return re.sub('(\(\))+$', '', ('%d(%s)(%s)' % (t.val, self.tree2str(t.left), self.tree2str(t.right)))) if t else ''
    

    Java version:

    public String tree2str(TreeNode t) {
        return t == null ? "" : (t.val + "(" + tree2str(t.left) + ")(" + tree2str(t.right) + ")").replaceAll("(\\(\\))+$", "");
    }

Log in to reply
 

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