-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0606-construct-string-from-binary-tree.py
More file actions
41 lines (29 loc) · 884 Bytes
/
0606-construct-string-from-binary-tree.py
File metadata and controls
41 lines (29 loc) · 884 Bytes
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
38
39
40
41
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def tree2str(self, root: Optional[TreeNode]) -> str:
res = []
self.dfs(root, res)
return ''.join(res)
def dfs(self, root: Optional[TreeNode], res: []):
if root is None:
return
res.append(str(root.val))
if root.left is None and root.right is None:
return
res.append('(')
self.dfs(root.left, res)
res.append(')')
if root.right is not None:
res.append('(')
self.dfs(root.right, res)
res.append(')')
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
print(Solution().tree2str(root))