Created
January 14, 2016 17:24
-
-
Save neizod/0fc4fa649bb269725826 to your computer and use it in GitHub Desktop.
uva 122 trees on the level
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from collections import deque | |
class Node(object): | |
def __init__(self): | |
self.value = None | |
self.left = None | |
self.right = None | |
def testcase(): | |
tree = Node() | |
while True: | |
for pair in input().strip().split(): | |
if pair == '()': | |
break | |
now = tree | |
value, position = pair[1:-1].split(',') | |
for direction in position: | |
if direction == 'L': | |
if now.left is None: | |
now.left = Node() | |
now = now.left | |
else: | |
if now.right is None: | |
now.right = Node() | |
now = now.right | |
now.value = value | |
if pair == '()': | |
break | |
valid = True | |
result = [] | |
queue = deque() | |
queue.append(tree) | |
while queue: | |
now = queue.popleft() | |
if now.left is not None: | |
queue.append(now.left) | |
if now.right is not None: | |
queue.append(now.right) | |
if now.value is None: | |
valid = False | |
break | |
else: | |
result.append(now.value) | |
if valid: | |
print(' '.join(result)) | |
else: | |
print('not complete') | |
def main(): | |
try: | |
while True: | |
testcase() | |
except EOFError: | |
exit(0) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment