백준 #1991 트리순회

정은경·2022년 5월 9일
0

알고리즘

목록 보기
46/125

문제

https://www.acmicpc.net/problem/1991

  • 문제 난이도: 하(easy)
  • 문제 유형: 트리, 구현
  • 추천 풀이 시간: 20분

나의 풀이

# your code goes here
count = int(input())
# print(count)

pre_order = ""
mid_order = ""
post_order = ""

for _ in range(count):
	# print(_, post_order)
	node, left, right = [x if x != "." else None for x in input().split(" ")]
	if(node and node in pre_order):
		if(left and right):
			pre_order = pre_order.replace(node, node+left+right)
			mid_order = mid_order.replace(node, left+node+right)
			post_order = post_order.replace(node, left+right+node)
		elif(left):
			pre_order = pre_order.replace(node, node+left)
			mid_order = mid_order.replace(node, left+node)
			post_order = post_order.replace(node, left+node)
		elif(right):
			pre_order = pre_order.replace(node, node+right)
			mid_order = mid_order.replace(node, node+right)
			post_order = post_order.replace(node, right+node)
	else:
		pre_order += node
		if(left):
			pre_order += left
			mid_order += left
			post_order += left
		mid_order += node
		if(right):
			pre_order += right
			mid_order += right
			post_order += right
		post_order += node
# print("".join(pre_order))
# print("".join(mid_order))
print(pre_order)
print(mid_order)
print(post_order)

다른 사람의 풀이

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 != ".":
        pre_order(tree[node.left])
    if node.right != ".":
        pre_order(tree[node.right])

def in_order(node):
    if node.left != ".":
        in_order(tree[node.left])
    print(node.data, end="")
    if node.right != ".":
        in_order(tree[node.right])

def post_order(node):
    if node.left != ".":
        post_order(tree[node.left])
    if node.right != ".":
        post_order(tree[node.right])
    print(node.data, end="")

count = int(input())

tree = {}
for _ in range(count):
    data, left, right = input().split(" ")
    node = Node(data, left, right)
    tree[data] = node

pre_order(tree["A"])
print("")
in_order(tree["A"])
print("")
post_order(tree["A"])
print("")
profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글