https://www.acmicpc.net/problem/1991
내 풀이:
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
|
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self, root, left, right):
self.root = Node(root)
if left != '.':
self.root.left = Node(left)
if right != '.':
self.root.right = Node(right)
self.current = self.root
def append(self, parent, left, right):
self.current = self.root
stack = []
if self.current.right:
stack.append(self.current.right)
if self.current.left:
stack.append(self.current.left)
while stack:
self.current = stack.pop()
if self.current.data == parent:
if left != '.':
self.current.left = Node(left)
if right != '.':
self.current.right = Node(right)
return
if self.current.right:
stack.append(self.current.right)
if self.current.left:
stack.append(self.current.left)
def PreOrder(self, now):
print(now.data, end='')
if now.left:
self.PreOrder(now.left)
if now.right:
self.PreOrder(now.right)
def InOrder(self, now):
if now.left:
self.InOrder(now.left)
print(now.data, end='')
if now.right:
self.InOrder(now.right)
def PostOrder(self, now):
if now.left:
self.PostOrder(now.left)
if now.right:
self.PostOrder(now.right)
print(now.data, end='')
N = int(input())
root, left, right = input().split()
tree = Tree(root, left, right)
for _ in range(N-1):
parent, left, right = input().split()
tree.append(parent, left, right)
tree.PreOrder(tree.root)
print()
tree.InOrder(tree.root)
print()
tree.PostOrder(tree.root)
print()
|
Python3, 64ms
클래스를 이용한 트리의 구현.
파이썬으로 풀어보는 백준 1700번: 멀티탭 스케줄링 (0) | 2020.05.16 |
---|---|
파이썬으로 풀어보는 백준 1967번: 트리의 지름 (0) | 2020.05.02 |
파이썬으로 풀어보는 백준 1949번: 우수 마을 (0) | 2020.04.12 |
파이썬으로 풀어보는 [2020 KAKAO BLIND RECRUITMENT] 블록 이동하기 (0) | 2020.03.31 |
파이썬으로 풀어보는 SWEA 5688. 세제곱근을 찾아라 (0) | 2020.03.20 |
댓글 영역