-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path606.py
More file actions
60 lines (56 loc) · 1.87 KB
/
606.py
File metadata and controls
60 lines (56 loc) · 1.87 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
__________________________________________________________________________________________________
sample 44 ms submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def tree2str(self, t: TreeNode) -> str:
def DFS(root, string):
if root:
string = str(root.val)
if (not root.right) and (not root.left):
return string
elif root.right:
string += '(' + DFS(root.left, string) + ')'
string += '(' + DFS(root.right, string) + ')'
else:
string += '(' + DFS(root.left, string) + ')'
else:
return ''
return string
string = ""
return DFS(t, string)
__________________________________________________________________________________________________
sample 14748 kb submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def tree2str(self, t: TreeNode) -> str:
if not t:
return ''
stack = [t]
visited = set()
s = ''
while stack:
t = stack[-1]
if t in visited:
stack.pop()
s+=')'
else:
visited.add(t)
s+='('+str(t.val)
if not t.left and t.right:
s+= '()'
if t.right:
stack.append(t.right)
if t.left:
stack.append(t.left)
return s[1:len(s)-1]
__________________________________________________________________________________________________