백준 | 1991 트리 순회 [Python]

yeonk·2022년 6월 21일
0

algorithm

목록 보기
81/88
post-thumbnail

💡 Python 3






🔗 문제


1991 트리 순회 [Link]



트리 개념은 어느정도 이해했는데 막상 바로 구현하려니까 쉽지 않다.
이전에 정리해둔 블로그를 참고하여 문제를 풀었다.
복습이 필요할 것 같다.






💻 코드


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

n = int(input())
tree = {}

for _ in range(n):
    root, lt, rt = input().split()
    tree[root] = [lt, rt]

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






참고 자료


자료구조 | 트리

백준 - 1991번 - 트리 순회[파이썬(python)]

백준 파이썬 1991 트리 순회

0개의 댓글