一定要理清逻辑,我在这题上修修补补,打补丁打了半天,最后才发现,如果一开始有清晰的逻辑的话,那么代码会非常简单的。
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+")"