반응형

   문제

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





이번엔 이진트리이다.

루트와 모든 원소만 알고있다면 트리를 구성할수있다.

전위순회의 가장 첫원소는 루트이다.

트리를 구한뒤 후위순회를 통해 출력해보자.

입력방식은 조금 특이하다. 예외처리를 이용해 처리하자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Node:
    def __init__(self,item):
        self.val=item
        self.left=None
        self.right=None
 
 
class BinaryTree:
    def __init__(self):
        self.head=Node(None)
 
 
    def insert(self,item):#루트존재여부 확인
        if self.head.val is None:
            self.head.val = item
        else:
            self.addnode(self.head,item)
 
    def addnode(self,cur,item):
        if cur.val>item:#새로운 인자가 현재보다 작다면 왼쪽
            if cur.left!=None:#왼쪽이 비어있지않다면
                self.addnode(cur.left,item)
            else:#비어있다면 넣어준다.
                cur.left=Node(item)
        elif cur.val<item:#새로운 인자가 현재보다 크다면 오른쪽
            if cur.right!=None:
                self.addnode(cur.right,item)
            else:
                cur.right=Node(item)
    def postorder(self,cur):#후위순회
        if cur.left != None:
            self.postorder(cur.left)
        if cur.right != None:
            self.postorder(cur.right)
        print(cur.val)
 
 
import sys
sys.setrecursionlimit(10**9)
 
 
b_tree=BinaryTree()#초기화
count = 0
while count <= 10000:
    try:
        num = int(input())
    except:break
    b_tree.insert(num)
    count += 1
 
b_tree.postorder(b_tree.head)
cs




이렇게 코드를 구현하면 시간초과가 난다.

이진트리를 만드는데 O(NlogN)

후위순회를 하는데 O(NlogN)의 시간이 든다.

트리를 만들지 않고 바로 출력하는 방식으로 만들어야겠다.

이진트리의 전위순회를 살펴보면

첫번째 루트 노드를 기준으로 작은값은 왼쪽 큰값은 오른쪽으로 나뉘는것을 볼 수 있다.

50 / 30 24 5 28 / 45 98 52 60

이렇게 분할하여 문제를 해결할수있다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def postorder(start,end):
    if start>end:
        return
 
    division=end+1#나눌위치
    for i in range(start+1,end+1):
        if post[start]<post[i]:
            division=i
            break
 
    postorder(start+1,division-1)#분할 왼쪽
    postorder(division,end)#분할 오른쪽
    print(post[start])
 
 
 
import sys
sys.setrecursionlimit(10**9)
 
 
post=[]
count = 0
while count <= 10000:
    try:
        num = int(input())
    except:break
    post.append(num)
    count += 1
 
postorder(0,len(post)-1)
cs



반응형

'알고리즘(python) > 자료구조' 카테고리의 다른 글

[Python]트리 백준 2263  (1) 2020.03.17
[Python]트리 백준 1991  (0) 2020.03.16
[Python]트리 백준 1967  (3) 2020.03.15
[Python]트리 백준 1167  (1) 2020.03.15
[Python]트리 백준 11725  (0) 2020.03.15
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기