백준 5639번 이진 검색 트리

highway92·2021년 9월 29일
0

백준

목록 보기
10/27

문제출처 : https://www.acmicpc.net/problem/5639

풀이과정

1. 입력의 처음은 루트 노드이다.

2. 입력을 모두 받고 난 후 for 문을 돌면서 root 보다 큰 값을 찾으면 rightindex로 설정한다.

3. list[1:rightindex] 까지는 루트 왼쪽 list[rightindex:]은 루트의 오른쪽 트리가 된다. 각각의 트리에 다시 preorder함수를 적용시킨다.

4. 그냥 실행 시키면 recursive Error가 떠서 값을 설정해주니 통과하였다....

import sys
sys.setrecursionlimit(20_000)
def postorder(orderlist):
    if len(orderlist) == 0:
        return []
    post=[]
    root = orderlist[0]
    rightindex = None
    if len(orderlist) > 1:
        for i in range(1,len(orderlist)):
            if orderlist[i] > root:
                rightindex = i
                break
        

    if rightindex != None:
        left = orderlist[1:rightindex]
        post = post + postorder(left)
        right = orderlist[rightindex:]
        post = post + postorder(right)
    else:
        left = orderlist[1:]
        post = post + postorder(left)
    post.append(root)
    return post

preorder=[]

while True:
    try:
        preorder.append(int(sys.stdin.readline()))
    except:
        break

if len(preorder) == 0:
    print()
else:
    for i in postorder(preorder):
        print(i)
profile
웹 개발자로 활동하고 있습니다.

0개의 댓글