https://www.acmicpc.net/problem/1991
1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파
www.acmicpc.net
재귀함수돌때 언제 출력해야하는지만 유의하면 쉬운 문제!
풀이
전위 순회는 출력하고 왼오
중위 순회는 왼 출력하고 오
후위 순회는 왼오하고 출력
트리는 그냥 딕셔너리로 저장..
def preorder(x):
print(x, end="")
if tree[x][0] != ".":
preorder(tree[x][0])
if tree[x][1] != ".":
preorder(tree[x][1])
def inorder(x):
if tree[x][0] != ".":
inorder(tree[x][0])
print(x, end="")
if tree[x][1] != ".":
inorder(tree[x][1])
def postorder(x):
if tree[x][0] != ".":
postorder(tree[x][0])
if tree[x][1] != ".":
postorder(tree[x][1])
print(x, end="")
n = int(input())
tree = {}
for i in range(n):
data, left, right = input().split()
tree[data] = [left, right]
preorder("A")
print()
inorder("A")
print()
postorder("A")
'PS > 재귀' 카테고리의 다른 글
[백준] 2448번: 별 찍기 - 11 파이썬 (2) | 2024.02.28 |
---|---|
[백준] 1992번: 쿼드트리 파이썬 (0) | 2024.02.28 |
[백준] 1780번: 종이의 개수 파이썬 (0) | 2024.02.28 |
[백준] 2630번: 색종이 만들기 파이썬 (0) | 2024.02.27 |