์•Œ๊ณ ๋ฆฌ์ฆ˜

[Data Structure] ํŠธ๋ฆฌ (Tree)

jjingle 2024. 1. 29. 13:34

ํŠธ๋ฆฌ (Tree) ๊ตฌ์กฐ

  • Node์™€ Branch๋ฅผ ์ด์šฉํ•ด์„œ, ์‚ฌ์ดํด์„ ์ด๋ฃจ์ง€ ์•Š๋„๋ก ๊ตฌ์„ฑํ•œ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ
  • ์ด์ง„ ํŠธ๋ฆฌ(Binary Tree) ํ˜•ํƒœ์˜ ๊ตฌ์กฐ, ํƒ์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌํ˜„์— ๋งŽ์ด ์‚ฌ์šฉ

 

ํŠธ๋ฆฌ ๊ด€๋ จ ์šฉ์–ด

  • Node : ํŠธ๋ฆฌ์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๋Š” ๊ธฐ๋ณธ ์š”์†Œ(๋ฐ์ดํ„ฐ์™€ ๋‹ค๋ฅธ ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ์— ๋Œ€ํ•œ Branch ์ •๋ณด ํฌํ•จ)
  • Root Node : ํŠธ๋ฆฌ ๋งจ ์œ„์— ์žˆ๋Š” ๋…ธ๋“œ
  • Level : ์ตœ์ƒ์œ„ ๋…ธ๋“œ๋ฅผ Level 0 ์œผ๋กœ ํ–ˆ์„ ๋•Œ, ํ•˜์œ„ Branch๋กœ ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ์˜ ๊นŠ์ด
  • Parent Node : ์–ด๋–ค ๋…ธ๋“œ์˜ ๋‹ค์Œ ๋ ˆ๋ฒจ์— ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ
  • Child Node : ์–ด๋–ค ๋…ธ๋“œ์˜ ์ƒ์œ„ ๋ ˆ๋ฒจ์— ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ
  • Leaf Node(Terminal Node) : Child Node๊ฐ€ ํ•˜๋‚˜๋„ ์—†๋Š” ๋…ธ๋“œ
  • Sibling (Brother Node) : ๋™์ผํ•œ Parent Node๋ฅผ ๊ฐ€์ง„ ๋…ธ๋“œ
  • Depth : ํŠธ๋ฆฌ์—์„œ Node๊ฐ€ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ Level

tree

 

 

์ด์ง„ ํŠธ๋ฆฌ & ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ (Binary Search Tree)

  • ์ด์ง„ ํŠธ๋ฆฌ : ๋…ธ๋“œ์˜ ์ตœ๋Œ€ Branch๊ฐ€ 2์ธ ํŠธ๋ฆฌ
  • ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ(Binary Search Tree; BST) : ์™ผ์ชฝ ๋…ธ๋“œ๋Š” ํ•ด๋‹น ๋…ธ๋“œ๋ณด๋‹ค ์ž‘์€ ๊ฐ’, ์˜ค๋ฅธ์ชฝ ๋…ธ๋“œ๋Š” ํ•ด๋‹น ๋…ธ๋“œ๋ณด๋‹ค ํฐ ๊ฐ’
    • ์žฅ์  : ํƒ์ƒ‰ ์†๋„ ๊ฐœ์„ 
    • ์ฃผ์š” ์šฉ๋„ : ๋ฐ์ดํ„ฐ ๊ฒ€์ƒ‰ (ํƒ์ƒ‰)

 

ํŒŒ์ด์ฌ ๊ฐ์ฒด์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์œผ๋กœ ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ ๊ตฌํ˜„

# ๋…ธ๋“œ ํด๋ž˜์Šค ๋งŒ๋“ค๊ธฐ
class Node:
	def __init__(self, value):
    	self.value = value
        self.left = None
        self.right = None

 

  • ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ์— ๋ฐ์ดํ„ฐ ๋„ฃ๊ธฐ
class NodeMgmt:
    def __init__(self, head):
        self.head = head
    
    def insert(self, value):
        self.current_node = self.head
        while True:
            if value < self.current_node.value:
                if self.current_node.left != None:
                    self.current_node = self.current_node.left
                else:
                    self.current_node.left = Node(value)
                    break
            else:
                if self.current_node.right != None:
                    self.current_node = self.current_node.right
                else:
                    self.current_node.right = Node(value)
                    break
                    
 
head = Node(1)
BST = NodeMgmt(head)
BST.insert(2)

 

  • ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ ํƒ์ƒ‰
def search(self, value):
    self.current_node = self.head
    while self.current_node:
        if self.current_node.value == value:
            return True
        elif value < self.current_node.value:
            self.current_node = self.current_node.left
        else:
            self.current_node = self.current_node.right
    return False