728x90
반응형
1. priority_queue를 사용하고
2. 마지막 노드에 값을 넣고
3. 끝에서부터 역순으로 heapify!
def swap(tree, index_1, index_2):
"""완전 이진 트리의 노드 index_1과 노드 index_2의 위치를 바꿔준다"""
temp = tree[index_1]
tree[index_1] = tree[index_2]
tree[index_2] = temp
def reverse_heapify(tree, index):
"""삽입된 노드를 힙 속성을 지키는 위치로 이동시키는 함수"""
parent_index = index // 2 # 삽입된 노드의 부모 노드의 인덱스 계산
# 부모 노드가 존재하고, 부모 노드의 값이 삽입된 노드의 값보다 작을 때
if 0 < parent_index < len(tree) and tree[index] > tree[parent_index]:
swap(tree, index, parent_index) # 부모 노드와 삽입된 노드의 위치 교환
reverse_heapify(tree, parent_index) # 삽입된 노드를 대상으로 다시 reverse_heapify 호출
class PriorityQueue:
"""힙으로 구현한 우선순위 큐"""
def __init__(self):
self.heap = [None] # 파이썬 리스트로 구현한 힙
def insert(self, data):
"""삽입 메소드"""
self.heap.append(data) # 힙의 마지막에 데이터 추가
reverse_heapify(self.heap, len(self.heap)-1) # 삽입된 노드(추가된 데이터)의 위치를 재배치
def __str__(self):
return str(self.heap)
# 테스트 코드
priority_queue = PriorityQueue()
priority_queue.insert(6)
priority_queue.insert(9)
priority_queue.insert(1)
priority_queue.insert(3)
priority_queue.insert(10)
priority_queue.insert(11)
priority_queue.insert(13)
print(priority_queue)
728x90
반응형
'자료구조' 카테고리의 다른 글
[파이썬] 이진 트리 만들어 보기 (1) | 2023.12.15 |
---|---|
[파이썬] 힙 우선순위 데이터 추출 구현 (0) | 2023.12.15 |
[파이썬] 힙 정렬 구현하기 (1) | 2023.12.15 |
[파이썬] heapify 함수 구현 (1) | 2023.12.15 |
[파이썬] in-order 순회 구현하기 (1) | 2023.12.15 |