ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๋ฐ˜์‘ํ˜•

์ด์ง„ ํŠธ๋ฆฌ๋Š” ํŠธ๋ฆฌ์— ํฌํ•จ๋˜๋Š” ๋ชจ๋“  ๋…ธ๋“œ์˜ ์ฐจ์ˆ˜๊ฐ€ 2 ์ดํ•˜์ธ ํŠธ๋ฆฌ๋ฅผ ๋งํ•œ๋‹ค. ์ฆ‰ ๋ชจ๋“  ๋…ธ๋“œ๋Š” ์ž์‹์ด ์—†๊ฑฐ๋‚˜ (๋ฆฌํ”„๋…ธ๋“œ์˜ ๊ฒฝ์šฐ), ํ•˜๋‚˜๋งŒ ์žˆ๊ฑฐ๋‚˜ ์•„๋‹ˆ๋ฉด ๋‘˜ ์žˆ๋Š” ์„ธ ๊ฒฝ์šฐ ์ค‘ ํ•˜๋‚˜์— ํ•ด๋‹นํ•œ๋‹ค.

 

 

์ด์ง„ ํŠธ๋ฆฌ์˜ ์ถ”์ƒ์  ์ž๋ฃŒ๊ตฌ์กฐ

์—ฐ์‚ฐ์˜ ์ •์˜

  • size() - ํ˜„์žฌ ํŠธ๋ฆฌ์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ๋…ธ๋“œ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•จ
  • depth() - ํ˜„์žฌ ํŠธ๋ฆฌ์˜ ๊นŠ์ด (๋˜๋Š” ๋†’์ด; height)๋ฅผ ๊ตฌํ•จ
  • ์ˆœํšŒ (traversal)

 

 

 

์ด์ง„ ํŠธ๋ฆฌ์˜ ์ž๋ฃŒ๊ตฌ์กฐ ๊ตฌํ˜„

# ๋…ธ๋“œ ํด๋ž˜์Šค

# ์ด์ง„ํŠธ๋ฆฌ์˜ ๊ตฌํ˜„ - ๋…ธ๋“œ(node)
class Node:
    def __init__(self, item):
        self.data = item
        self.left = None
        self.right = None

 

 

 

# ํŠธ๋ฆฌ ํด๋ž˜์Šค

๋ฃจํŠธ๋งŒ ์•Œ๋ฉด ๋œ๋‹ค

# ์ด์ง„ ํŠธ๋ฆฌ์˜ ๊ตฌํ˜„ - ํŠธ๋ฆฌ(tree)
class BinaryTree:
    def __init__(self, r):
        self.root = r

 

 

 

# size()

class Node:

	# ์ด์ง„ ํŠธ๋ฆฌ์˜ ํฌ๊ธฐ - ์žฌ๊ท€ํ•จ์ˆ˜ ์ด์šฉ
    def size(self):
        l = self.left.size() if self.left else 0
        r = self.right.size() if self.right else 0
        return l + r + 1
 

class BinaryTree:
	
    # ํฌ๊ธฐ ๊ตฌํ•˜๊ธฐ
    def size(self):
        if self.root:
            return self.root.size()
        else:
            return 0

 

 

 

 

# depth()

# ์ด์ง„ํŠธ๋ฆฌ์˜ ๊ตฌํ˜„ - ๋…ธ๋“œ(node)
class Node:
    # ์ƒ์„ฑ์ž
    def __init__(self, item):
        self.data = item
        self.left = None
        self.right = None
        
    # ๋…ธ๋“œ์˜ ๊ฐฏ์ˆ˜ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜ - ์žฌ๊ท€ํ•จ์ˆ˜ ์ด์šฉ
    def size(self):
        l = self.left.size() if self.left else 0
        r = self.right.size() if self.right else 0
        return l + r + 1
    
    # depth
    def depth(self):
        l = self.left.depth() if self.left else 0
        r = self.right.depth() if self.right else 0
        return max(l,r) + 1
    
    # ์ค‘์œ„ ์ˆœํšŒ
    def inorder(self):
        traversal = []
        
        # ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๊ฐ€ ์กด์žฌํ•œ๋‹ค๋ฉด
        if self.left:
            traversal += self.left.inorder()
        
        traversal.append(self.data)
        
        # ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๊ฐ€ ์žˆ๋‹ค๋ฉด
        if self.right:
            traversal += self.right.inorder()
            
        return traversal
        

# ์ด์ง„ ํŠธ๋ฆฌ์˜ ๊ตฌํ˜„ - ํŠธ๋ฆฌ(tree)
class BinaryTree:
    # ์ƒ์„ฑ์ž
    def __init__(self, r):
        self.root = r
        
    # ํฌ๊ธฐ ๊ตฌํ•˜๊ธฐ
    def size(self):
        # ๋ฃจํŠธ๊ฐ€ ์กด์žฌํ•˜๋ฉด ๋ฆฌํ„ด
        if self.root:
            return self.root.size()
        else:
            return 0
        
    # depth
    def depth(self):
        if self.root:
            return self.root.depth()
        else:
            return 0
            
        
    # ์ค‘์œ„ ์ˆœํšŒ
    def inorder(self):
        if self.root:
            return self.root.inorder()
        else:
            return []
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€