一定要理清邏輯,我在這題上修修補補,打補丁打了半天,最後才發現,如果一開始有清晰的邏輯的話,那麼代碼會非常簡單的。
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+")"