---
# System prepended metadata

title: 530. Minimum Absolute Difference in BST
tags: [Leetcode, Python]

---

# 530. Minimum Absolute Difference in BST
###### tags: `Python`,`Leetcode`
https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/
## BST
``` python=
# 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:
        ans = []
        def inorder(root):
            if root == None:
                return None
            if root != None:
                inorder(root.left)
            ans.append(root.val)
            if root.right != None:
                inorder(root.right)
        inorder(root)
        mini = abs(ans[0]-ans[1])
        for i in range(1,len(ans)):
            mini = min( mini,ans[i] - ans[i-1])
        return mini
```
## DFS
```python=
# 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:
        ans = []
        def dfs(root):
            if root == None:
                return None
            ans.append(root.val)
            dfs(root.left)
            dfs(root.right)
        
        dfs(root)
        ans.sort()
        mini = abs(ans[0]-ans[1])
        for i in range(1,len(ans)):
            mini = min( mini,ans[i] - ans[i-1]) #將 ans[i] - ans[i-1] 的差值與 mini 的值比較
        return mini
```