Leetcode 606. 根據二叉樹創建字符串

一定要理清邏輯,我在這題上修修補補,打補丁打了半天,最後才發現,如果一開始有清晰的邏輯的話,那麼代碼會非常簡單的。

class Solution:
    def tree2str(self,t):
        if t is None:
            return ""

        s=str(t.val)

        a=self.tree2str(t.left)
        b=self.tree2str(t.right)
        lena=len(a)
        lenb=len(b)
        if lena is 0 and lenb is 0:
            return s
        elif lena is 0 and lenb is not 0:
            return s+"()"+"("+b+")"
        elif lena is not 0 and lenb is 0:
            return s+"("+a+")"
        else:
            return s+"("+a+")"+"("+b+")"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章