606. Construct String from Binary Tree
https://leetcode.com/problems/construct-string-from-binary-tree/
Python
Recursion
class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
def preorder(node, result):
if not node:
return
result.append(str(node.val))
if node.left:
result.append('(')
preorder(node.left, result)
result.append(')')
else:
if node.right:
result.append('()')
if node.right:
result.append('(')
preorder(node.right, result)
result.append(')')
result = []
preorder(root, result)
return ''.join(result)