본문 바로가기

스터디 1일 1커밋

240320 [BOJ/백준] 1991. 트리 순회

 

https://www.acmicpc.net/problem/1991

 

1991번: 트리 순회

첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파

www.acmicpc.net


나의 코드

# 트리순회

def preorder(x):
    print(parent[x], end='')
    if left[x] != '.':
        preorder(parent.index(left[x]))
    if right[x] != '.':
        preorder(parent.index(right[x]))

def inorder(x):
    if left[x] != '.':
        inorder(parent.index(left[x]))
    print(parent[x], end='')
    if right[x] != '.':
        inorder(parent.index(right[x]))

def postorder(x):
    if left[x] != '.':
        postorder(parent.index(left[x]))
    if right[x] != '.':
        postorder(parent.index(right[x]))
    print(parent[x], end='')


N = int(input())
parent = [0]*N
left = [0]*N
right = [0]*N
for i in range(N):
    parent[i] , left[i], right[i] = input().split()

preorder(0)
print()
inorder(0)
print()
postorder(0)

 

결과


예전에 강의에서 데이터들을 어떻게 넣어서 어떤 방식으로 처리했는지 어렴풋이 기억나서 그걸로 풀어보려고 했다. 재귀함수로 큰 틀로 어떻게 진행하는지 생각하며 코드를 짜봤는데 재귀함수에서 처음에 종료조건을 잘못 주고 문제풀다가 오류나서 예전에 풀던 코드보고 해결...ㅎㅎ