Data structures (with python) - 8.Tree - 8.4 Complete Binary Tree

2024. 1. 11. 01:56ใ†CS - Roadmap.sh/1. Data structures

Data structures (with python) - 8.Tree - 8.4 Complete Binary Tree

 

๐Ÿ’ก A complete binary tree is a special type of binary tree where all the levels of the tree are filled completely except the lowest level nodes which are filled from as left as possible.

์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ๋Š” ๊ฐ€๋Šฅํ•œ ํ•œ ์™ผ์ชฝ๋ถ€ํ„ฐ ์ฑ„์›Œ์ง€๋Š” ์ตœํ•˜์œ„ ๋ ˆ๋ฒจ ๋…ธ๋“œ๋ฅผ ์ œ์™ธํ•˜๊ณ  ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๋ ˆ๋ฒจ์ด ์™„์ „ํžˆ ์ฑ„์›Œ์ง€๋Š” ํŠน์ˆ˜ํ•œ ์œ ํ˜•์˜ ์ด์ง„ ํŠธ๋ฆฌ์ž…๋‹ˆ๋‹ค.

 

Full Binary Tree ์™€ Complete Binary Tree ์˜  ํ•œ๊ธ€ ๋ฒˆ์—ญ์— ์กฐ๊ธˆ ์ฃผ์˜๋ฅผ ํ•ด์•ผํ•˜๋Š”๋ฐ,

๊ฐœ์ธ์ ์œผ๋กœ ์ •๋ฆฌํ•˜๋‹ค๋ณด๋‹ˆ ๋ฒˆ์—ญ์„ ๋‘˜๋‹ค ์™„์ „์ด์ง„์œผ๋กœ ์ž˜๋ชป ํ•˜๊ณ  ์žˆ๋Š” ๊ฒฝ์šฐ๋„ ์žˆ์—ˆ๋‹ค.

 

์ • ์ด์ง„ ํŠธ๋ฆฌ(ๆ•ดไบŒ้€ฒ-, full binary tree, ๋•Œ๋กœ๋Š” proper ๋˜๋Š” plane ์ด์ง„ ํŠธ๋ฆฌ๋ผ๊ณ ๋„ ํ•จ)

์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ(ๅฎŒๅ…จไบŒ้€ฒ-, Complete binary tree)

ํฌํ™” ์ด์ง„ ํŠธ๋ฆฌ(้ฃฝๅ’ŒไบŒ้€ฒ-, perfect binary tree)

 



์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ(Full Binary Tree): ์ด ํŠธ๋ฆฌ๋Š” ๋ชจ๋“  ๋…ธ๋“œ๊ฐ€ 0๊ฐœ ๋˜๋Š” 2๊ฐœ์˜ ์ž์‹ ๋…ธ๋“œ๋ฅผ ๊ฐ€์ง€๋Š” ํŠธ๋ฆฌ๋ฅผ ๋งํ•ฉ๋‹ˆ๋‹ค. ์ด ๋ง์€, ํ•œ ๋…ธ๋“œ๊ฐ€ ์ž์‹ ๋…ธ๋“œ๋ฅผ ๊ฐ€์ง„๋‹ค๋ฉด, ๊ทธ๊ฒƒ์€ ๋ฐ˜๋“œ์‹œ ๋‘ ๊ฐœ์˜ ์ž์‹ ๋…ธ๋“œ๋ฅผ ๊ฐ€์ ธ์•ผ ํ•œ๋‹ค๋Š” ๋œป์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์ด ํŠธ๋ฆฌ์—์„œ๋Š” ์–ด๋–ค ๋…ธ๋“œ๋„ ํ•˜๋‚˜์˜ ์ž์‹๋งŒ์„ ๊ฐ€์งˆ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.


์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ(Complete Binary Tree): ์ด ํŠธ๋ฆฌ๋Š” ๋ชจ๋“  ๋ ˆ๋ฒจ์ด ์™„์ „ํžˆ ์ฑ„์›Œ์ ธ ์žˆ๊ณ , ๋งˆ์ง€๋ง‰ ๋ ˆ๋ฒจ์˜ ๋…ธ๋“œ๋Š” ์™ผ์ชฝ๋ถ€ํ„ฐ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ฐจ๋ก€๋Œ€๋กœ ์ฑ„์›Œ์ ธ ์žˆ๋Š” ํŠธ๋ฆฌ๋ฅผ ๋งํ•ฉ๋‹ˆ๋‹ค. ์ด ๋ง์€, ํŠธ๋ฆฌ์˜ ๋†’์ด h์— ๋Œ€ํ•ด 1๋ถ€ํ„ฐ h-1๊นŒ์ง€์˜ ๊ฐ ๋ ˆ๋ฒจ์ด ์™„์ „ํžˆ ์ฑ„์›Œ์ ธ ์žˆ๊ณ , ๋งˆ์ง€๋ง‰ ๋ ˆ๋ฒจ์€ ์™ผ์ชฝ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ์ฑ„์›Œ์ ธ ์žˆ์–ด์•ผ ํ•œ๋‹ค๋Š” ๋œป์ž…๋‹ˆ๋‹ค.

 

์ด ๊ธ€์—์„œ ๋‹ค๋ฃฐ ํŠธ๋ฆฌ๋Š” ์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ์ด๋‹ค.

๊ฐ„๋žตํžˆ ์ •๋ฆฌํ•˜์ž๋ฉด , ๋ชจ๋“  ๋ ˆ๋ฒจ์ด ์™„์ „ํžˆ ์ฑ„์›Œ์ ธ ์žˆ๊ณ , ๋งˆ์ง€๋ง‰ ๋ ˆ๋ฒจ์€ ์™ผ์ชพ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด ์ˆœ์„œ๋Œ€๋กœ ์ฑ„์›Œ์ ธ ์žˆ๋Š” ํŠธ๋ฆฌ์ด๋‹ค.

 

In Python
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# ๋…ธ๋“œ ์ƒ์„ฑ
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)

 

 

graphviz๋กœ ์ƒ์„ฑ

 

 

 

 

 

# appendix ๋กœ ๋…ธ๋“œ ํŠธ๋ฆฌ๋“ค ์‹œ๊ฐํ™” ํ•˜๋Š”๊ฒƒ ์ ๊ธฐ

728x90