728x90
반응형
기본적인 트리 문제이다.
- 전위 순회한 결과 : (왼쪽 자식) -> (오른쪽 자식)
- 중위 순회한 결과 : (왼쪽 자식) -> (루트) -> (오른쪽 자식)
- 후위 순회한 결과 : (왼쪽 자식) -> (오른쪽 자식) -> (루트)
def preorder(node):
print(node, end='')
left, right = tree[node][0], tree[node][1]
if left != '.':
preorder(left)
if right != '.':
preorder(right)
def inorder(node):
left, right = tree[node][0], tree[node][1]
if left != '.':
inorder(left)
print(node, end='')
if right != '.':
inorder(right)
def postorder(node):
left, right = tree[node][0], tree[node][1]
if left != '.':
postorder(left)
if right != '.':
postorder(right)
print(node, end='')
N = int(input())
tree = {}
for i in range(1, N+1):
node, left, right = input().split()
tree[node] = [left, right]
preorder('A'); print()
inorder('A'); print()
postorder('A'); print()
728x90
반응형
'Agorithm > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 11053번 가장 긴 증가하는 부분 수열(python) (0) | 2021.03.17 |
---|---|
백준 알고리즘 1149번 RGB거리(python) (0) | 2021.03.17 |
백준 알고리즘 2670번 연속부분최대곱(python) (0) | 2021.03.17 |
백준 알고리즘 15489번 파스칼 삼각형(python) (0) | 2021.03.17 |
백준 알고리즘 16395번 파스칼의 삼각형(python) (0) | 2021.03.17 |