# C#LeetCode刷题之#530-二叉搜索树的最小绝对差（Minimum Absolute Difference in BST）

1
\
3
/
2

1

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Input:

1
\
3
/
2

Output:
1

Explanation:

The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.

```public class Program {

public static void Main(string[] args) {
var root = new TreeNode(4) {
left = new TreeNode(8),
right = new TreeNode(1)
};

var res = GetMinimumDifference(root);
Console.WriteLine(res);

}

public static int GetMinimumDifference(TreeNode root) {
var list = new List<int>();
PreOrder(root, ref list);
var res = int.MaxValue;
list.Sort();
for(var i = 0; i < list.Count - 1; i++) {
res = Math.Min(res, list[i + 1] - list[i]);
}
return res;
}

public static void PreOrder(TreeNode root, ref List<int> list) {
if(root == null) return;
PreOrder(root?.left, ref list);
PreOrder(root?.right, ref list);
}

public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}

}```

`3`