๋ฌธ์ ํด๊ฒฐ ๊ณผ์
โ๏ธ ๋ฌธ์ ์์ฝ
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์ด๋ฏ๋ก ๊ฐ๋นํ ์ ์๋ ์ ๋์ด๋ค.
๋ค๋ฅธ ์ฌ๋์ ์ฝ๋๋ฅผ ํ๊ตฌํด๋ณด๊ธฐ
๋ค๋ฅธ ์ฌ๋์ ์ฝ๋๋ ์ค์์ํํ๋ ์ฝ๋์๊ณ , ๋ด๊ฐ ๋ณธ ์ฝ๋ ์ค์๋ ๋ด ์ฝ๋๊ฐ ๊ฐ์ฅ ๊น๋ํ๋ค.