1991번: 트리 순회

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

www.acmicpc.net


 

Dictionary에 root를 key로 하고, [left, right]를 value로 저장한다.

 

import sys
from collections import defaultdict
input = sys.stdin.readline
result = ""
def preorder(x):
print(x, end="")
if arr[x][0] != ".":
preorder(arr[x][0])
if arr[x][1] != ".":
preorder(arr[x][1])
def inorder(x):
if arr[x][0] != ".":
inorder(arr[x][0])
print(x, end="")
if arr[x][1] != ".":
inorder(arr[x][1])
def postorder(x):
if arr[x][0] != ".":
postorder(arr[x][0])
if arr[x][1] != ".":
postorder(arr[x][1])
print(x, end="")
arr = defaultdict(list)
N = int(input())
for _ in range(N):
x, y, z = input().split()
arr[x].extend([y, z])
preorder("A")
print()
inorder("A")
print()
postorder("A")
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기