2024. 1. 9. 21:32ใCS - Roadmap.sh/1. Data structures
Data structures (with python) - 8.Tree - 8.1 Binary Tree
Tree
๐ก A tree is non-linear and a hierarchical data structure consisting of a collection of nodes such that each node of the tree stores a value and a list of references to other nodes (the “children”).
ํธ๋ฆฌ๋ ๋น์ ํ์ ์ด๋ฉฐ ๋ ธ๋ ๋ชจ์์ผ๋ก ๊ตฌ์ฑ๋ ๊ณ์ธต์ ๋ฐ์ดํฐ ๊ตฌ์กฐ๋ก, ํธ๋ฆฌ์ ๊ฐ ๋ ธ๋๊ฐ ๊ฐ๊ณผ ๋ค๋ฅธ ๋ ธ๋์ ๋ํ ์ฐธ์กฐ ๋ชฉ๋ก('์์')์ ์ ์ฅํฉ๋๋ค.
Binary Tree
๐ก A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.
์ด์ง ํธ๋ฆฌ๋ ๊ฐ ๋ ธ๋์ ์ต๋ ๋ ๊ฐ์ ์์์ด ์๋ ํธ๋ฆฌ ๋ฐ์ดํฐ ๊ตฌ์กฐ๋ก, ์ผ์ชฝ ์์๊ณผ ์ค๋ฅธ์ชฝ ์์์ด๋ผ๊ณ ํฉ๋๋ค.
์ด์งํธ๋ฆฌ(binary tree)๋ ๊ฐ ๋ ธ๋๊ฐ ์ต๋ ๋๊ฐ์ ์์ ๋ ธ๋๋ฅผ ๊ฐ์ง๋ ํธ๋ฆฌํํ์ ์๋ฃ ๊ตฌ์กฐ์ ๋๋ค.
์ด์ง ํธ๋ฆฌ์ ๊ฐ ๋ ธ๋๋ '์ผ์ชฝ', '์ค๋ฅธ์ชฝ' ์์๋ ธ๋๋ฅผ ๊ฐ์ง์ ์์ผ๋ฉฐ, ์ด๋ค์ ๋ถ๋ชจ ๋ ธ๋๋ฅผ ์ฐธ์กฐํฉ๋๋ค.
ํนํ ์ด์ง ๊ฒ์ํธ๋ฆฌ(Binary Search Tree, BST, ๋ฐ๋ก ๋ค์์ฅ์์ ๋ค๋ฃธ), ํ(heap), ํธ๋ผ์ด(Trie) ๋ฑ ๋ง์ ์๋ฃ๊ตฌ์กฐ์ ๊ธฐ๋ฐ์ด ๋๋ค.
์ด๋ฌํ ์๋ฃ๊ตฌ์กฐ๋ค์ ๋ฐ์ดํฐ ์ ๋ ฌ, ๊ฒ์, ์ฐ์ ์์ ํ ๋ฑ ๋ค์ํ ๋ฌธ์ ๋ฅผ ํจ๊ด๊ฑฐ์ผ๋ก ํด๊ฒฐํ๋๋ฐ ์ฌ์ฉ๋๋ค.
In Python
์ด์งํธ๋ฆฌ๋ฅผ ํ์ด์ฌ์์ ๊ตฌํํ๋ ค๋ฉด Node ํด๋์ค๋ฅผ ์์ฑํ๋ค.
์ด ํด๋์ค๋ ๋ ธ๋์ ๊ฐ์ ์ ์ฅํ๋ 'data' ํ๋์ ์ผ/์ค๋ฅธ์ชฝ ์์ ๋ ธ๋๋ฅผ ์ฐธ์กฐํ๋ 'left', 'right'ํ๋๋ฅผ ๊ฐ์ง๋ค.
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)
1์ ๋ฃจํธ ๋ ธ๋๋ก ๊ฐ์ง๋ ์ด์ง ํธ๋ฆฌ๋ฅผ ์์ฑ ํด ๋ณด์๋ค.
์ด์ง ํธ๋ฆฌ์ ๋ฃจํธ ๋ ธ๋๋ 1, 1์ ์์๋ ธ๋๋ 2์ 3, 2์ ์์๋ ธ๋๋ 4์ 5์ด๋ค.
ํ์ฉ
์ด์ง ํธ๋ฆฌ๋ฅผ ํ์ฉํ ์๊ณ ๋ฆฌ์ฆ์๋ ๋ํ์ ์ผ๋ก ํธ๋ฆฌ ์ํ (Tree Traversal)๊ฐ ์๋ค.
๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๋ ์์์ ๋ฐ๋ผ ์ ์ ์ํ(Pre-order), ์ค์ ์ํ(In-order), ํ์ ์ํ(Post-order)๋ก ๋๋๋ค.
์ ์ ์ํ๋ ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๊ณ , ๊ทธ ๋ ธ๋์ ์ผ์ชฝ ์๋ธํธ๋ฆฌ, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ ์์๋ก ์ํํ๋ค.
์ค์ ์ํ๋ ์ผ์ชฝ, ๋ ธ๋, ์ค๋ฅธ์ชฝ ์์๋ก ์ํ
ํ์ ์ํ๋ ์ผ์ชฝ, ์ค๋ฅธ์ชฝ, ๋ ธ๋ ์์๋ก ๋ฐฉ๋ฌธํ๋ค.
์ด์ง ํธ๋ฆฌ์ ์ํ๋ ์ฌ๊ท์ ์ผ๋ก ๊ตฌํํ ์ ์๋ค.
์? => ์ด๋ ๊ฐ ๋ ธ๋์์ ๋์ผํ ์ฐ์ฐ์ ์ํํ๊ธฐ ๋๋ฌธ์ด๋ค.
๊ฐ ํธ๋ฆฌ์ํ์ ๋ฐฉ๋ฒ์ ํ์ด์ฌ์์ ๊ตฌํํด ๋ด ๋๋ค.
# ์ ์ ์ํ
def pre_order(node):
if node is not None:
print(node.data, end=' ')
pre_order(node.left)
pre_order(node.right)
# ์ค์ ์ํ
def in_order(node):
if node is not None:
in_order(node.left)
print(node.data, end=' ')
in_order(node.right)
# ํ์ ์ํ
def post_order(node):
if node is not None:
post_order(node.left)
post_order(node.right)
print(node.data, end=' ')
์ ํจ์๋ค์ ์ ์, ์ค์, ํ์ ์ํ๋ฅผ ์ํํ๊ณ ์ด์ง ํธ๋ฆฌ์ ๋ ธ๋ ๊ฐ์ ์ถ๋ ฅํฉ๋๋ค.
'CS - Roadmap.sh > 1. Data structures' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Data structures (with python) - 8.Tree - 8.3 Full Binary Tree (1) | 2024.01.10 |
---|---|
Data structures (with python) - 8.Tree - 8.2 Binary Search Tree (0) | 2024.01.09 |
Data structures (with python) - 7. Hash Table (0) | 2024.01.08 |
Data structures (with python) - 6. Queue (2) | 2024.01.08 |
Data structures (with python) - 5. Stack (1) | 2024.01.07 |