본문 바로가기
Python3/백준 알고리즘

2022.02.19 [백준] (python 파이썬) 트리 순회

by ian's coding 2022. 2. 19.
728x90
반응형

 

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

 

1991번: 트리 순회

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

www.acmicpc.net


풀이

 

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
n=int(input())
tree={}
for i 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')
cs

 

 

 

 

728x90
반응형

댓글