Tech for good

[Leetcode/Tree] 501. Find Mode in Binary Search Tree ๋ณธ๋ฌธ

IT/Computer Science

[Leetcode/Tree] 501. Find Mode in Binary Search Tree

Diana Kang 2025. 3. 14. 23:07

  • mode: ์ตœ๋นˆ๊ฐ’

๐Ÿ”น Binary Search Tree(์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ, BST)๋ž€?

 

  • ์ด์ง„ ํŠธ๋ฆฌ์˜ ํ•œ ์ข…๋ฅ˜์ด๋ฉฐ, ๋…ธ๋“œ์˜ ๋ฐฐ์น˜์— ํŠน์ •ํ•œ ๊ทœ์น™์ด ์ ์šฉ๋œ๋‹ค:
    • ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๊ฐ’์€ ํ˜„์žฌ ๋…ธ๋“œ๋ณด๋‹ค ์ž‘์•„์•ผ ํ•œ๋‹ค.
    • ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๊ฐ’์€ ํ˜„์žฌ ๋…ธ๋“œ๋ณด๋‹ค ์ปค์•ผ ํ•œ๋‹ค.
  • ์ด ๊ทœ์น™ ๋•๋ถ„์— ํƒ์ƒ‰(๊ฒ€์ƒ‰), ์‚ฝ์ž…, ์‚ญ์ œ ๋“ฑ์˜ ์—ฐ์‚ฐ์ด ํšจ์œจ์ (ํ‰๊ท  O(log n))์œผ๋กœ ์ˆ˜ํ–‰๋œ๋‹ค.

 

์ถœ์ฒ˜: https://yoongrammer.tistory.com/71

 


๐Ÿ”น ์ค‘์œ„ ์ˆœํšŒ(In-order Traversal)๋ž€?

์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ(BST)์—์„œ ์ค‘์œ„ ์ˆœํšŒ(In-order Traversal) ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉด ๊ฐ’์ด ์˜ค๋ฆ„์ฐจ์ˆœ(ascending order)์œผ๋กœ ์ •๋ ฌ๋œ ์ˆœ์„œ๋กœ ๋ฐฉ๋ฌธ๋œ๋‹ค.

๐ŸŒŸ ์ค‘์œ„ ์ˆœํšŒ ์ˆœ์„œ

  1. ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ํƒ์ƒ‰
  2. ํ˜„์žฌ ๋…ธ๋“œ ๋ฐฉ๋ฌธ
  3. ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ํƒ์ƒ‰

๐Ÿ”น ์˜ˆ์ œ ํŠธ๋ฆฌ

์•„๋ž˜์™€ ๊ฐ™์€ BST๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ณด์ž.

        4
       / \
      2   6
     / \   \
    1   3   7

์ค‘์œ„ ์ˆœํšŒ(In-order Traversal) ์‹คํ–‰ ๊ฒฐ๊ณผ:

1 โ†’ 2 โ†’ 3 โ†’ 4 โ†’ 6 โ†’ 7  (์˜ค๋ฆ„์ฐจ์ˆœ)

์ฆ‰, BST๋Š” In-order Traversal์„ ํ•˜๋ฉด ์ •๋ ฌ๋œ ์ƒํƒœ๋กœ ๊ฐ’์ด ๋‚˜์˜ค๋ฏ€๋กœ, ์ด์ „ ๊ฐ’๊ณผ ํ˜„์žฌ ๊ฐ’์„ ๋น„๊ตํ•˜๋ฉด์„œ ์ตœ๋นˆ๊ฐ’์„ ์ฐพ์„ ์ˆ˜ ์žˆ์Œ!


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        
        self.current_val = None
        self.current_count = 0
        self.max_count = 0
        self.modes = []

        def inorder_traversal(node):
            if node is None:
                return
            
            # 1. ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ํƒ์ƒ‰
            inorder_traversal(node.left)
            
            # 2.1. ํ˜„์žฌ ๋…ธ๋“œ ๋ฐฉ๋ฌธ
            if node.val == self.current_val:
                self.current_count += 1
            else:
                self.current_val = node.val
                self.current_count = 1
            
            # 2.2. mode(s) ๊ฐฑ์‹ 
            if self.current_count > self.max_count:
                self.max_count = self.current_count
                self.modes = [node.val]
            elif self.current_count == self.max_count:
                self.modes.append(node.val)
            
            # 3. ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ํƒ์ƒ‰
            inorder_traversal(node.right)
        
        # 4. ์ค‘์œ„ ์ˆœํšŒ ์‹œ์ž‘
        inorder_traversal(root)
        return self.modes