반응형
1. 문제
https://www.acmicpc.net/problem/1991
1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1≤N≤26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 영문자
www.acmicpc.net
2. 풀이
3. 구현
import sys
#sys.stdin=open('input.txt')
n = int(sys.stdin.readline().strip())
tree={}
while n:
n-=1
root,left,right = sys.stdin.readline().strip().split()
tree[root] = [left, right]
def preorder(root):
if root!='.':
sys.stdout.write(root)
preorder(tree[root][0]) #left
preorder(tree[root][1]) #right
def inorder(root):
if root!='.':
inorder(tree[root][0])
sys.stdout.write(root)
inorder(tree[root][1])
def postorder(root):
if root!='.':
postorder(tree[root][0])
postorder(tree[root][1])
sys.stdout.write(root)
preorder('A')
print()
inorder('A')
print()
postorder('A')
반응형
'PS > 백준' 카테고리의 다른 글
백준 16139번: 인간-컴퓨터 상호작용 python 파이썬 (0) | 2021.08.06 |
---|---|
백준 10211번: Maximum Subarray python 파이 (0) | 2021.08.06 |
백준 11725번: 트리의 부모찾기 python 파이썬 (0) | 2021.08.06 |
백준 2250번: 트리의 높이와 너비 python 파이썬 (0) | 2021.08.06 |
[반례모음] 백준 2839번: 설탕 배달 python 파이썬 (0) | 2021.08.06 |
댓글