๐Ÿ’ซ ETC/Leetcode

Week 3-1. [Binary Search Tree (BST)] 530. Minimum Absolute Difference in BST (Python3)

ming412 2023. 9. 8. 02:48

๋ฌธ์ œ ํ•ด๊ฒฐ ๊ณผ์ •

โœ๏ธ ๋ฌธ์ œ ์š”์•ฝ

https://leetcode.com/problems/minimum-absolute-difference-in-bst/?envType=study-plan-v2&envId=top-interview-150 

 

Minimum Absolute Difference in BST - LeetCode

Can you solve this real interview question? Minimum Absolute Difference in BST - Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.   Example 1: [https://assets.l

leetcode.com

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

 

โžก๏ธ BST๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง„ BST์— ํฌํ•จ๋œ ๋…ธ๋“œ ์ค‘ ์„œ๋กœ ๋‹ค๋ฅธ ๋‘ ๋…ธ๋“œ์˜ ์ฐจ์˜ ์ตœ์†Ÿ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋ผ.

 

๐Ÿ”Ž ์–ด๋–ค ์‹์œผ๋กœ ์ ‘๊ทผํ–ˆ๋Š”๊ฐ€?

๋ฌธ์ œ์—์„œ BST๊ฐ€ ์ฃผ์–ด์กŒ๋‹ค. BST์˜ ํŠน์ง•์€, ๋ถ€๋ชจ ๋…ธ๋“œ๊ฐ€ ์™ผ์ชฝ ์ž์‹ ๋…ธ๋“œ๋ณด๋‹ค ํฌ๊ณ  ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ๋ณด๋‹ค ์ž‘๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

 

๋”ฐ๋ผ์„œ BST๋ฅผ ์ค‘์œ„ ์ˆœํšŒํ•˜๋ฉด ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ๋œ ๊ฐ’์„ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.

(์ค‘์œ„์ˆœํšŒ๋Š” ์™ผ์ชฝ ์ž์‹ -> ๋‚˜ -> ์˜ค๋ฅธ์ชฝ ์ž์‹ ์ˆœ์œผ๋กœ ์ˆœํšŒํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.)

 

๊ทธ๋ฆฌ๊ณ  ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ, ์ด์›ƒํ•˜๋Š” ๊ฐ’์˜ ์ฐจ์ด๋ฅผ ๊ณ„์‚ฐํ•˜์—ฌ ์ตœ์†Ÿ๊ฐ’์„ ๊ฐฑ์‹ ํ•œ๋‹ค.

 

๐ŸŽฏ ํ’€์ด

# 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 getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        nums = list()
        self.inorder(root, nums) # root ๋…ธ๋“œ๋ถ€ํ„ฐ ์ค‘์œ„ ์ˆœํšŒ
        # ๋ชจ๋“  ๋…ธ๋“œ ์ค‘์œ„์ˆœํšŒ ํ›„์— nums์—๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์›์†Œ๊ฐ€ ์ €์žฅ๋˜์–ด ์žˆ๋‹ค.
        mn = 1e9
        for i in range(len(nums)-1):
            mn = min(mn, nums[i+1]-nums[i])
        return mn

    # ์ค‘์œ„ ์ˆœํšŒ
    def inorder(self, node: TreeNode, lst: list) -> None:
        if node == None: return
        self.inorder(node.left, lst) # ์™ผ์ชฝ ์ž์‹ ๋…ธ๋“œ
        lst.append(node.val) # ๋‚˜
        self.inorder(node.right, lst) # ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ

 

์œ„ ์ฝ”๋“œ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” ์ค‘์œ„ ์ˆœํšŒ๋ฅผ ํ†ตํ•ด ์ด์ง„ ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธํ•˜๋ฏ€๋กœ O(n)์ด๋‹ค. 

๋ฌธ์ œ์—์„œ ์ž…๋ ฅ์˜ ์ตœ๋Œ€๋Š” 10^4์ด๋ฏ€๋กœ ๊ฐ๋‹นํ•  ์ˆ˜ ์žˆ๋Š” ์ •๋„์ด๋‹ค.

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ์ฝ”๋“œ๋ฅผ ํƒ๊ตฌํ•ด๋ณด๊ธฐ

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ์ฝ”๋“œ๋„ ์ค‘์œ„์ˆœํšŒํ•˜๋Š” ์ฝ”๋“œ์˜€๊ณ , ๋‚ด๊ฐ€ ๋ณธ ์ฝ”๋“œ ์ค‘์—๋Š” ๋‚ด ์ฝ”๋“œ๊ฐ€ ๊ฐ€์žฅ ๊น”๋”ํ–ˆ๋‹ค.