| 6 | return "".join(res) |
| 7 | |
| 8 | def dfs(self, t: TreeNode, res: list): |
| 9 | # If the current node is None, do nothing and return |
| 10 | if t is None: |
| 11 | return |
| 12 | res.append(str(t.val)) |
| 13 | |
| 14 | # If both left and right children are None, return as there are no more branches to explore |
| 15 | if t.left is None and t.right is None: |
| 16 | return |
| 17 | res.append('(') |
| 18 | |
| 19 | # Recursively call the DFS function for the left child |
| 20 | self.dfs(t.left, res) |
| 21 | res.append(')') |
| 22 | |
| 23 | # If the right child exists, process it |
| 24 | if t.right is not None: |
| 25 | res.append('(') |
| 26 | |
| 27 | # Recursively call the DFS function for the right child |
| 28 | self.dfs(t.right, res) |
| 29 | res.append(')') |
| 30 | |