requirements

You need to convert a binary tree to a string of parentheses and integers using a sequential traversal.

Empty nodes are represented by a pair of empty parentheses “()”. And you need to omit any empty parenthesis pairs that do not affect the one-to-one mapping between the string and the original binary tree.

Example 1:

Input: binary tree: 1/2 3/4 \ [1, 2, 3, 4] output: "1 (2) (4) and (3)" explanation: that will be "1 (2 (4) the ()) () (3)", after you omit all unnecessary parentheses to empty, it will be "1 (2) (4) and (3)".Copy the code

Example 2:

Input: binary tree: [1,2,3, NULL,4] 1 / \ 2 3\4 Output: "1(2()(4))(3)" Explanation: Similar to the first example, except that we cannot omit the first pair of parentheses to break the one-to-one mapping between input and output.Copy the code

The core code

class TreeNode:
    def __init__(self, val=0, left=None, right=None) :
        self.val = val
        self.left = left
        self.right = right
        
class Solution:
    def tree2str(self, root: Optional[TreeNode]) - >str:
        if not root:
            return ""
        res = ""
        left = self.tree2str(root.left)
        right = self.tree2str(root.right)
        if left or right:
            res += "(%s)" % left
        if right:
            res += "(%s)" % right
        return str(root.val) + res
Copy the code

If left or right:res += “(%s)” % left if left or right:res += “(%s)” % left