Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

JH 개발 블로그

백준 파이썬 1991 트리 순회 본문

코딩테스트/백준

백준 파이썬 1991 트리 순회

쿠우우훈 2021. 12. 30. 10:15

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())
tree = {}
for _ in range(N):
    root, left, right = input().split()
    tree[root] = [left,right]


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')

preorder(전위순회) = (루트)(왼쪽자식)(오른쪽자식)

inorder(중위순회) = (왼쪽자식)(루트)(오른쪽자식)

postorder(후위순회) = (왼쪽자식)(오른쪽자식)(루트)

 

루트를 출력할때 순서만 다릅니다.

예를들어 전위순회에서는 맨 위에 있는 루트를 출력하고, 왼쪽자식으로 간 후

왼쪽자식에서도 다시 (루트)(왼쪽자식)(오른쪽자식) 순으로 재귀적으로 출력해나갑니다.

Comments