Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1cfa73a

Browse files
authored
Create Day-26_Verify Preorder Serialization of a Binary Tree.py
1 parent 559b6ba commit 1cfa73a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution(object):
2+
def isValidSerialization(self, preorder):
3+
"""
4+
:type preorder: str
5+
:rtype: bool
6+
"""
7+
# remember how many empty slots we have
8+
# non-null nodes occupy one slot but create two new slots
9+
# null nodes occupy one slot
10+
11+
p = preorder.split(',')
12+
13+
#initially we have one empty slot to put the root in it
14+
slot = 1
15+
for node in p:
16+
17+
# no empty slot to put the current node
18+
if slot == 0:
19+
return False
20+
21+
# a null node?
22+
if node == '#':
23+
# ocuppy slot
24+
slot -= 1
25+
else:
26+
# create new slot
27+
slot += 1
28+
29+
#we don't allow empty slots at the end
30+
return slot==0

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /