题目:https://leetcode.com/submissions/detail/99935635/
思路:将BST中序遍历,得到中序遍历的数组,然后比较相邻值的差,找到最小差。
int getMinimumDifference(TreeNode* root)
{
vector<int> result;
inorderTraversal(root,result);
int differ = INT_MAX;
for(vector<int>::iterator it=result.begin()+1; it<=result.end(); ++it)
{
int tmp = abs(*it - *(it-1));
if(tmp < differ)
{
differ = tmp;
}
}
if(differ == INT_MAX)
{
differ = 0;
}
return differ;
}
void inorderTraversal(TreeNode* root, vector<int>& res)
{
if(!root)return;
inorderTraversal(root->left,res);
res.push_back(root->val);
inorderTraversal(root->right,res);
}