728x90
반응형
def get_parent_index(complete_binary_tree, index):
"""배열로 구현한 완전 이진 트리에서 index번째 노드의 부모 노드의 인덱스를 리턴하는 함수"""
parent_index = index // 2
# 부모 노드가 있으면 인덱스를 리턴한다
if 0 < parent_index < len(complete_binary_tree):
return parent_index
return None
def get_left_child_index(complete_binary_tree, index):
"""배열로 구현한 완전 이진 트리에서 index번째 노드의 왼쪽 자식 노드의 인덱스를 리턴하는 함수"""
left_child_index = 2 * index
# 왼쪽 자식 노드가 있으면 인덱스를 리턴한다
if 0 < left_child_index < len(complete_binary_tree):
return left_child_index
return None
def get_right_child_index(complete_binary_tree, index):
"""배열로 구현한 완전 이진 트리에서 index번째 노드의 오른쪽 자식 노드의 인덱스를 리턴하는 함수"""
right_child_index = 2 * index + 1
# 오른쪽 자식 노드가 있으면 인덱스를 리턴한다
if 0 < right_child_index < len(complete_binary_tree):
return right_child_index
return None
# 테스트 코드
root_node_index = 1 # root 노드
tree = [None, 1, 5, 12, 11, 9, 10, 14, 2, 10] # 과제 이미지에 있는 완전 이진 트리
# root 노드의 왼쪽과 오른쪽 자식 노드의 인덱스를 받아온다
left_child_index = get_left_child_index(tree, root_node_index)
right_child_index = get_right_child_index(tree,root_node_index)
print(tree[left_child_index])
print(tree[right_child_index])
# 9번째 노드의 부모 노드의 인덱스를 받아온다
parent_index = get_parent_index(tree, 9)
print(tree[parent_index])
# 부모나 자식 노드들이 없는 경우들
parent_index = get_parent_index(tree, 1) # root 노드의 부모 노드의 인덱스를 받아온다
print(parent_index)
left_child_index = get_left_child_index(tree, 6) # 6번째 노드의 왼쪽 자식 노드의 인덱스를 받아온다
print(left_child_index)
right_child_index = get_right_child_index(tree, 8) # 8번째 노드의 오른쪽 자식 노드의 인덱스를 받아온다
print(right_child_index)
728x90
반응형
'자료구조' 카테고리의 다른 글
[파이썬] heapify 함수 구현 (1) | 2023.12.15 |
---|---|
[파이썬] in-order 순회 구현하기 (1) | 2023.12.15 |
[파이썬] 이진 탐색 트리 삽입 구현 (0) | 2023.12.12 |
[파이썬] 더블리 링크드 리스트 prepend 구현 (0) | 2023.12.10 |
[파이썬] 더블리 링크드 리스트 삭제 구현 (0) | 2023.12.10 |