---
# System prepended metadata

title: Leetcode 530. Minimum Absolute Difference in BST
tags: [Binary Tree, Tree, DFS, Leetcode]

---

## 題解

### Inorder traversal and mark previous value


因為 BST 的中序遍歷會是升序排列，所以要找出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:
        output = float('inf')
        pre = -1
        def dfs(root):
            nonlocal output, pre
            if not root:
                return
            dfs(root.left)
            if pre == -1:
                pre = root.val
            else:
                output = min(output,root.val - pre)
                pre = root.val
            dfs(root.right)
        dfs(root)
        return output
            
```