# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:deftree2str(self,root: Optional[TreeNode]) ->str:deftraverse(root):ifnot root:return'' left =traverse(root.left) right =traverse(root.right)iflen(left)==0andlen(right)==0:returnstr(root.val)eliflen(left)==0:returnstr(root.val)+'()'+'('+ right +')'eliflen(right)==0:returnstr(root.val)+'('+ left +')'returnstr(root.val)+'('+ left +')'+'('+ right +')'returntraverse(root)