728x90
1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파
www.acmicpc.net
이진트리에서 순회하는 종류는 세 가지가 있다.
루트 노드를 기준으로 루트 노드 - 왼쪽 자식 트리 - 오른쪽 자식 트리를 순차적으로 방문하는 전위 순회,
왼쪽 자식 트리 - 루트 노드 - 오른쪽 자식 트리를 순차적으로 방문하는 중위 순회,
그리고 마지막으로 왼쪽 자식 트리 - 오른쪽 자식 트리 - 루트 노드를 방문하는 후위 순회다.
재귀함수 심화 대표 문제인 하노이탑 이동 순서처럼, 방문하는 순서에 맞게 재귀를 돌려주고 그 안에서 루트 노드를 로그 프린팅 하며 원하는 답을 출력할 수 있다.
nodes = dict()
for _ in range(int(input())):
root, left, right = map(str, input().split())
nodes[root] = [left, right]
# 전위 순회
def printPreorder(root):
# 루트
print(root, end= "")
if nodes[root] == ['.', '.']:
return
# 왼쪽
if nodes[root][0] != '.':
printPreorder(nodes[root][0])
# 오른쪽
if nodes[root][1] != '.':
printPreorder(nodes[root][1])
# 중위 순회
def printInorder(root):
# 왼쪽
if nodes[root][0] != '.':
printInorder(nodes[root][0])
# 루트
print(root, end= "")
if nodes[root] == ['.', '.']:
return
# 오른쪽
if nodes[root][1] != '.':
printInorder(nodes[root][1])
# 후위 순회
def printPostorder(root):
# 왼쪽
if nodes[root][0] != '.':
printPostorder(nodes[root][0])
# 오른쪽
if nodes[root][1] != '.':
printPostorder(nodes[root][1])
# 루트
print(root, end="")
if nodes[root] == ['.', '.']:
return
printPreorder('A')
printInorder('A')
printPostorder('A')
728x90
'PS (Problem Solving)' 카테고리의 다른 글
[BOJ, Python] 14915 - 진수 변환기 (0) | 2023.01.28 |
---|---|
[BOJ, Python] 2293 - 동전 1 ( with Recursion, DP ) (0) | 2023.01.10 |
[BOJ, Python] 1644 - 소수의 연속합 ( with 에라토스테네스의 체, 투 포인터 ) (0) | 2023.01.08 |
[BOJ, Python] 11401 - 이항 계수 3 ( with Fermat's little theorem ) (1) | 2022.12.14 |
[BOJ, Python] 17626 - Four Squares ( with DP ) (0) | 2022.11.23 |