-
Notifications
You must be signed in to change notification settings - Fork 43
/
verify-preorder-serialization-of-a-binary-tree.py
48 lines (44 loc) · 1.27 KB
/
verify-preorder-serialization-of-a-binary-tree.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
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79537797
class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
stack = []
for node in preorder.split(','):
stack.append(node)
while len(stack) >= 3 and stack[-1] == stack[-2] == '#' and stack[-3] != '#':
stack.pop(), stack.pop(), stack.pop()
stack.append('#')
return len(stack) == 1 and stack.pop() == '#'
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
def split_iter(s, tok):
start = 0
for i in xrange(len(s)):
if s[i] == tok:
yield s[start:i]
start = i + 1
yield s[start:]
if not preorder:
return False
depth, cnt = 0, preorder.count(',') + 1
for tok in split_iter(preorder, ','):
cnt -= 1
if tok == "#":
depth -= 1
if depth < 0:
break
else:
depth += 1
return cnt == 0 and depth < 0