이코테의 트리 순회 강좌를 보고 짠 코드
import sys
input = sys.stdin.readline
class Node:
def __init__(self, data, left, right):
self.data=data
self.left=left
self.right=right
def pre_order(node):
print(node.data, end='')
if node.left!=None:
pre_order(tree[node.left])
if node.right!=None:
pre_order(tree[node.right])
def in_order(node):
if node.left!=None:
in_order(tree[node.left])
print(node.data,end='')
if node.right!=None:
in_order(tree[node.right])
def post_order(node):
if node.left!=None:
post_order(tree[node.left])
if node.right!=None:
post_order(tree[node.right])
print(node.data,end='')
n = int(input())
tree = {}
for i in range(n):
data, left, right = input().split()
if left=='.':
left=None
if right=='.':
right=None
tree[data] = Node(data,left,right)
pre_order(tree['A'])
print()
in_order(tree['A'])
print()
post_order(tree['A'])
클래스를 사용하지 않고 짠 코드
import sys
input = sys.stdin.readline
def pre_order(root):
if root!=None:
print(root,end='')
pre_order(tree[root][0])
pre_order(tree[root][1])
def in_order(root):
if root!=None:
in_order(tree[root][0])
print(root,end='')
in_order(tree[root][1])
def post_order(root):
if root!=None:
post_order(tree[root][0])
post_order(tree[root][1])
print(root,end='')
n = int(input())
tree = {}
for i in range(n):
data, left, right = input().split()
if left=='.':
left=None
if right=='.':
right=None
tree[data] = [left,right]
pre_order('A')
print()
in_order('A')
print()
post_order('A')
'[BOJ] - Python' 카테고리의 다른 글
[백준] 1931 : 회의실 배정 python (0) | 2023.08.12 |
---|---|
[백준] 11047 : 동전 0 python (0) | 2023.08.12 |
[백준] 11279 : 최대 힙 python (0) | 2023.08.10 |
[백준] 1927 : 최소 힙 python (0) | 2023.08.10 |
[백준] 11557 : Yangjojang of The Year python (0) | 2023.04.09 |