thals0 / TIL

📚 하루동안 공부한 내용을 기록하는 공간입니다.
0 stars 0 forks source link

[Algorithm] Tree #2

Closed thals0 closed 1 year ago

thals0 commented 1 year ago

[BOJ] 1991. 트리 순회

n = int(input())
tree = {}
for _ in range(n):
  root, left, right = input().split()
  tree[root] = [left, right]

def preorder(root):
  if root != '.':
    print(root, end='')
    preorder(tree[root][0])
    preorder(tree[root][1])

def inorder(root):
  if root != '.':
    inorder(tree[root][0])
    print(root, end='')
    inorder(tree[root][1])

def postorder(root):
  if root != '.':
    postorder(tree[root][0])
    postorder(tree[root][1])
    print(root, end='')

preorder('A')
print()
inorder('A')
print()
postorder('A')
thals0 commented 1 year ago

[BOJ] 트리의 순회 (복습 필요 🥊)

import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

n = int(input())
inorder = list(map(int, input().split()))
postorder = list(map(int, input().split()))

nodeNum = [0] * (n + 1)
for i in range(n):
    nodeNum[inorder[i]] = i

def getPreorder(inStart, inEnd, postStart, postEnd):
    if (inStart > inEnd) or (postStart > postEnd):
        return

    root = postorder[postEnd]

    leftNode = nodeNum[root] - inStart
    rightNode = inEnd - nodeNum[root]

    print(root, end = " ")
    getPreorder(inStart, inStart + leftNode - 1, postStart, postStart + leftNode - 1)
    getPreorder(inEnd - rightNode + 1, inEnd, postEnd - rightNode, postEnd - 1)

getPreorder(0, n-1, 0, n-1)
thals0 commented 1 year ago

[BOJ] 9934. 완전 이진 트리

from collections import defaultdict

k = int(input())
inorder = list(map(int, input().split()))
tree = defaultdict(list)
i = 0

def getTree(i, inorder):
  n = len(inorder)
  if n > 1:
    root = inorder[n//2]
    tree[i].append(root)
    i += 1
    getTree(i, inorder[:n//2])
    getTree(i, inorder[n//2+1:])
  elif n == 1:
    tree[i].append(inorder[0])

getTree(i, inorder)

tree = list(tree.values())
for i in range(k):
  print(*tree[i])