(DFS & BFS) 백준 1991번 트리순회

DARTZ·2022년 4월 29일
0

알고리즘

목록 보기
28/135
import sys
sys.stdin = open('in.txt', 'rt')
sys.setrecursionlimit(10000)
input = sys.stdin.readline

graph = []

N = int(input())
tree = {} # 딕셔너리 만들어준다. root, left와 right의 관계를 정의하기 위해

for n in range(N):
    root, left, right = sys.stdin.readline().strip().split()
    tree[root] = [left, right] # key 값에 root를 입력

def preorder(root):
    if root != '.': # 루트가 없을 경우 진행이 안됨
        print(root, end='') # 루트를 먼저 출력
        preorder(tree[root][0]) # 전위 순회이므로 왼쪽이 전부 탐색되고 나서 오른쪽 탐색 시작
        preorder(tree[root][1])

def inorder(root):
    if root != '.':
        inorder(tree[root][0])
        print(root, end='')
        inorder(tree[root][1])

def postorder(root):
    if root != '.':
        postorder(tree[root][0])
        postorder(tree[root][1])
        print(root, end='')


preorder('A')
print()
inorder('A')
print()
postorder('A')

루트와 자식간의 관계를 표현하기 위해 집합으로 표현하는 아이디어를 배운 것 같다. 우선 순위 탐색이므로 재귀 함수를 사용하여 DFS 방식으로 구현이 되었다.

profile
사람들이 비용을 지불하고 사용할 만큼 가치를 주는 서비스를 만들고 싶습니다.

0개의 댓글