-
Notifications
You must be signed in to change notification settings - Fork 43
/
construct-binary-tree-from-string.py
331 lines (285 loc) · 8.37 KB
/
construct-binary-tree-from-string.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""
Leetcode 536.
Construct Binary Tree from String
You need to construct a binary tree from a string consisting of parenthesis and integers.
The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.
You always start to construct the left child node of the parent first if it exists.
Example:
Input: "4(2(3)(1))(6(5))"
Output: return the tree root node representing the following tree:
4
/ \
2 6
/ \ /
3 1 5
Note:
There will only be '(', ')', '-' and '0' ~ '9' in the input string.
An empty tree is represented by "" instead of "()"
"""
# V0
# IDEA : tree property + recursive
class Solution(object):
def str2tree(self, s):
if not s:
return None
n = ''
while s and s[0] not in ('(', ')'):
n += s[0]
s = s[1:]
### NOTE this
node = TreeNode(int(n))
### NOTE this
left, right = self.divide(s)
node.left = self.str2tree(left[1:-1])
node.right = self.str2tree(right[1:-1])
return node
def divide(self, s):
part, deg = '', 0
while s:
"""
syntax exmaple :
In [9]: x = {'(' : 1, ')' : -1}
In [10]: x.get('(')
Out[10]: 1
In [11]: x.get('(', 0 )
Out[11]: 1
In [12]: x.get('&', 0 )
Out[12]: 0
"""
deg += {'(' : 1, ')' : -1}.get(s[0], 0)
part += s[0]
s = s[1:]
if deg == 0:
break
return part, s
# V0'
# IDEA : tree property + recursive
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def str2tree(self, s):
"""
:type s: str
:rtype: TreeNode
"""
def str2treeHelper(s, i):
start = i
if s[i] == '-': i += 1
while i < len(s) and s[i].isdigit():
i += 1
node = TreeNode(int(s[start:i]))
if i < len(s) and s[i] == '(':
i += 1
node.left, i = str2treeHelper(s, i)
i += 1
if i < len(s) and s[i] == '(':
i += 1
node.right, i = str2treeHelper(s, i)
i += 1
return node, i
return str2treeHelper(s, 0)[0] if s else None
# V0'
class Solution(object):
def str2tree(self, s):
"""
:type s: str
:rtype: TreeNode
"""
if not s: return None
n = ''
while s and s[0] not in ('(', ')'):
n += s[0]
s = s[1:]
node = TreeNode(int(n))
left, right = self.divide(s)
node.left = self.str2tree(left[1:-1])
node.right = self.str2tree(right[1:-1])
return node
def divide(self, s):
part, deg = '', 0
while s:
if s[0] == '(':
deg += 1
elif s[0] == ')':
deg += -1
else:
deg += 0
part += s[0]
s = s[1:]
if deg == 0: break
return part, s
# V1
# http://bookshadow.com/weblog/2017/03/12/leetcode-construct-binary-tree-from-string/
# https://blog.csdn.net/magicbean2/article/details/78850694
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def str2tree(self, s):
"""
:type s: str
:rtype: TreeNode
"""
if not s:
return None
n = ''
while s and s[0] not in ('(', ')'):
n += s[0]
s = s[1:]
node = TreeNode(int(n))
left, right = self.divide(s)
node.left = self.str2tree(left[1:-1])
node.right = self.str2tree(right[1:-1])
return node
def divide(self, s):
part, deg = '', 0
while s:
"""
syntax exmaple :
In [9]: x = {'(' : 1, ')' : -1}
In [10]: x.get('(')
Out[10]: 1
In [11]: x.get('(', 0 )
Out[11]: 1
In [12]: x.get('&', 0 )
Out[12]: 0
"""
deg += {'(' : 1, ')' : -1}.get(s[0], 0)
part += s[0]
s = s[1:]
if deg == 0:
break
return part, s
### Test case : dev
# V1'
# https://www.jiuzhang.com/solution/construct-binary-tree-from-string/#tag-highlight-lang-python
# IDEA : RECURSION
class Solution:
"""
@param s: a string
@return: return a TreeNode
"""
def str2tree(self, s):
self.idx = 0
self.len = len(s)
if(self.len == 0):
return None
root = self.dfs(s)
return root
def dfs(self, s):
if(self.idx >= self.len):
return None
sig, k = 1, 0
if(s[self.idx] == '-'):
sig = -1
self.idx += 1
while(self.idx < self.len and s[self.idx] >= '0' and s[self.idx] <= '9'):
k = k * 10 + ord(s[self.idx]) - ord('0')
self.idx += 1
root = TreeNode(sig * k)
if(self.idx >= self.len or s[self.idx] == ')'):
self.idx += 1
return root
self.idx += 1
root.left = self.dfs(s)
if(self.idx >= self.len or s[self.idx] == ')'):
self.idx += 1
return root
self.idx += 1
root.right = self.dfs(s)
if(self.idx >= self.len or s[self.idx] == ')'):
self.idx += 1
return root
return root
# V1''
# https://www.geeksforgeeks.org/construct-binary-tree-string-bracket-representation/
# Python3 program to conStruct a
# binary tree from the given String
# Helper class that allocates a new node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# This funtcion is here just to test
def preOrder(node):
if (node == None):
return
print(node.data, end = " ")
preOrder(node.left)
preOrder(node.right)
# function to return the index of
# close parenthesis
def findIndex(Str, si, ei):
if (si > ei):
return -1
# Inbuilt stack
s = []
for i in range(si, ei + 1):
# if open parenthesis, push it
if (Str[i] == '('):
s.append(Str[i])
# if close parenthesis
elif (Str[i] == ')'):
if (s[-1] == '('):
s.pop(-1)
# if stack is empty, this is
# the required index
if len(s) == 0:
return i
# if not found return -1
return -1
# function to conStruct tree from String
def treeFromString(Str, si, ei):
# Base case
if (si > ei):
return None
# new root
root = newNode(ord(Str[si]) - ord('0'))
index = -1
# if next char is '(' find the
# index of its complement ')'
if (si + 1 <= ei and Str[si + 1] == '('):
index = findIndex(Str, si + 1, ei)
# if index found
if (index != -1):
# call for left subtree
root.left = treeFromString(Str, si + 2, index - 1)
# call for right subtree
root.right = treeFromString(Str, index + 2, ei - 1)
return root
# V2
# https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/construct-binary-tree-from-string.py
# Time: O(n)
# Space: O(h)
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def str2tree(self, s):
"""
:type s: str
:rtype: TreeNode
"""
def str2treeHelper(s, i):
start = i
if s[i] == '-': i += 1
while i < len(s) and s[i].isdigit(): i += 1
node = TreeNode(int(s[start:i]))
if i < len(s) and s[i] == '(':
i += 1
node.left, i = str2treeHelper(s, i)
i += 1
if i < len(s) and s[i] == '(':
i += 1
node.right, i = str2treeHelper(s, i)
i += 1
return node, i
return str2treeHelper(s, 0)[0] if s else None