boj 1991

less than 1 minute read

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

from sys import stdin

class Node:
    def __init__(self, head, left, right):
        self.data = head
        self.left = left
        self.right = right

def preorder(root):
    print(root.data, end = '')
    if root.left != '.':
        preorder(tree[root.left])
    if root.right != '.':
        preorder(tree[root.right])

def inorder(root):
    if root.left != '.':
        inorder(tree[root.left])
    print(root.data, end = '')
    if root.right != '.':
        inorder(tree[root.right])

def postorder(root):
    if root.left != '.':
        postorder(tree[root.left])
    if root.right != '.':
        postorder(tree[root.right])
    print(root.data, end = '')

if __name__ == "__main__":
    tree = {}
    count = int(stdin.readline())
    for i in range(count):
        nodes = stdin.readline().split()
        tree[nodes[0]] = Node(nodes[0], nodes[1], nodes[2])
    
    preorder(tree['A'])
    print()
    inorder(tree['A'])
    print()
    postorder(tree['A'])


notion
  • 반드시 리뷰해야 하는 문제
  • 반복되는 재귀때문에 후위, 중위, 전위를 이해하는데 힘들었다.
  • 트리 문제가 가장 어려운듯...
  • 트리 클래스를 dictionary 형식으로 바꾸는 것이 키 포인트

Categories:

Updated: