aboutsummaryrefslogtreecommitdiffstats
path: root/606/main.py
blob: 44a82c706e2d1e4ffd53c2d533600725b8fa9001 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python

import typing


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: typing.Optional[TreeNode]) -> str:
        if not root:
            return ""
        if not root.left and not root.right:
            return str(root.val)
        if not root.right:
            return str(root.val) + "(" + self.tree2str(root.left) + ")"
        return (
            str(root.val)
            + "("
            + self.tree2str(root.left)
            + ")("
            + self.tree2str(root.right)
            + ")"
        )


def main():
    solution = Solution()
    print(solution.tree2str())


if __name__ == "__main__":
    main()