https://www.acmicpc.net/problem/1991
1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파
www.acmicpc.net
풀이
문제를 보았을때 알수있는 힌트
재귀함수에서 출력위치를 어떻게 하냐에 따라서 전위, 중위, 후위로 나오게 할수있다.
전위는 시작과 동시에 출력을 하고, 중위는 가운데에서 왼쪽후에 출력을 하고 후위는 오른쪽까지 간 후에 출력을 한다.
import sys
input = sys.stdin.readline
n = int(input())
n_list={}
for i in range(n):
temp = list(input().strip().split(" "))
tree=[]
for i in range(2):
tree.append(temp[i+1])
n_list[temp[0]]=tree
# 재귀함수
def front(x):
if x != '.':
print(x,end="")
front(n_list[x][0])
front(n_list[x][1])
def mid(x):
if x != '.':
mid(n_list[x][0])
print(x,end="")
mid(n_list[x][1])
def back(x):
if x != '.':
back(n_list[x][0])
back(n_list[x][1])
print(x,end="")
front("A")
print("")
mid("A")
print("")
back("A")
https://github.com/dydwkd486/coding_test/blob/main/baekjoon/baekjoon1991.py
GitHub - dydwkd486/coding_test: 코딩테스트 공부한 내용 정리
코딩테스트 공부한 내용 정리. Contribute to dydwkd486/coding_test development by creating an account on GitHub.
github.com
'Coding Test > baekjoon' 카테고리의 다른 글
[백준 1238] 파티- python (solved.ac - 골드 3) (0) | 2022.05.19 |
---|---|
[백준 1504] 특정한 최단 경로 - python (solved.ac - 골드 4) (0) | 2022.05.19 |
[백준 1916] 최소비용 구하기- python (solved.ac - 골드 5) (0) | 2022.05.13 |
[백준 1167] 트리의 지름 - python (solved.ac - 골드 3) (0) | 2022.05.12 |
[백준 2407] 조합 - python (solved.ac - 실버 3) (0) | 2022.05.12 |