# 530. Minimum Absolute Difference in BST 二叉搜索树的最小绝对差

@TOC

## # 题目描述

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

Example:

``````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.

## # 解题方法

### # Java解法

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int minDiff = Integer.MAX_VALUE;
TreeNode prev = null;

public int getMinimumDifference(TreeNode root) {
inOrder(root);
return minDiff;
}

public void inOrder(TreeNode root){
if(root == null){
return;
}
inOrder(root.left);
if(prev !=null) minDiff= Math.min(minDiff, root.val - prev.val);
prev = root;
inOrder(root.right);
}
}
``````

### # Python解法

``````# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res = float("inf")
self.prev = None
self.inOrder(root)
return self.res

def inOrder(self, root):
if not root: return
self.inOrder(root.left)
if self.prev:
self.res = min(self.res, root.val - self.prev.val)
self.prev = root
self.inOrder(root.right)
``````

## # 日期

2017 年 4 月 8 日 2018 年 11 月 14 日 —— 很严重的雾霾