## 题目描述

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.

## 解法一

### 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
"""
result = sys.maxsize
stack = []
prev = None
while root or stack:
if root:
stack.append(root)
root = root.left
else:
node = stack.pop()
if prev is not None:
result = min(result, node.val - prev)
prev = node.val
root = node.right
return result``````

### Java

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int getMinimumDifference(TreeNode root) {
int result = Integer.MAX_VALUE;
Stack<TreeNode> stack = new Stack<>();
Integer prev = null;
while (root != null || !stack.empty()) {
if (root != null) {
root = root.left;
} else {
TreeNode node = stack.pop();
if (prev != null) {
result = Math.min(result, node.val - prev);
}
prev = node.val;
root = node.right;
}
}
return result;
}
}``````

### C++

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getMinimumDifference(TreeNode *root) {
int result = INT_MAX;
stack<TreeNode *> sta;
int prev = 0;
bool hasPrev = false;
while (root != nullptr || !sta.empty()) {
if (root != nullptr) {
sta.push(root);
root = root->left;
} else {
TreeNode *node = sta.top();
sta.pop();
if (hasPrev) {
result = min(result, node->val - prev);
}
prev = node->val;
hasPrev = true;
root = node->right;
}
}
return result;
}
};``````