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")
'개발 > 알고리즘' 카테고리의 다른 글
[백준 1256] 사전 (python) (1) | 2021.04.29 |
---|---|
[백준 4358] 생태학 (python) (0) | 2021.04.28 |
[백준 1202] 보석 도둑 (python) (0) | 2021.04.27 |
[백준 1655] 가운데를 말해요 (python) (0) | 2021.04.27 |
[백준 21608] 상어 초등학교 (python) (0) | 2021.04.26 |
최근댓글