给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
class Solution {
public:
long long pre = LONG_MAX;
long long dif = LONG_MAX;
void inorder_t(TreeNode* root){
if(root == nullptr) return ;
inorder_t(root->left);
if(dif > abs(pre - root->val)) dif = abs(pre - root->val);
pre = root->val;
inorder_t(root->right);
}
int getMinimumDifference(TreeNode* root) {
inorder_t(root);
return dif;
}
int getMinimumDifference1(TreeNode* root) {
stack<TreeNode*> sta;
long long result = LONG_MAX;
TreeNode* cur = root;
TreeNode* pre = nullptr;
while(cur || !sta.empty())
{
if(cur){
sta.push(cur);
cur = cur->left;
}
else{
cur = sta.top();sta.pop();
if(pre && result > abs(cur->val - pre->val)) result = abs(cur->val - pre->val);
pre = cur;
cur = cur->right;
}
}
return result;
}
};