개발공부/algorithm

[SWEA] [python] 1231.중위순회 - tree

so.py 2021. 3. 3. 15:32

문제

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

나의 코드

  • 트리를 생성한 후 중위순회를 진행해주는 문제다. 
  • 배열로 인덱스 별 값들을 받아줬고, 해당 배열에 대해 중위순회를 진행했다.
  • 왼쪽 노드는 node * 2, 오른쪽 노드는 node * 2 + 1 으로 처리해주었다.
def inorder(idx):
    if idx > N:
        return
    # if left node exists
    if (idx * 2) <= N:
        inorder(idx * 2)
    # append node value to ans
    ans.append(node[idx])
    # if right node exists
    if (idx *2 + 1) <= N:
        inorder(idx * 2 + 1)

for tc in range(10):
    N = int(input())
    node = [0] * (N+1)
    for n in range(N):
        vals = list(input().split())
        node[int(vals[0])] = vals[1]
    ans = []
    inorder(1)
    print("#{} {}".format(tc +1, ''.join(ans)))