**思路:**和上题一样,通过中序遍历成一个由小到大排序的数组,这样再通过for循环将较小值放进result里,最后返回result即可。
c++题解:
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> vec;
void traversal(TreeNode* root)
{
if(root==NULL) return;
traversal(root->left);
vec.push_back(root->val);
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
if(vec.size()<2) return 0;
int result=INT_MAX;
for(int i=0;i<vec.size()-1;i++)
{
result=min(vec[i+1]-vec[i],result);
}
return result;
}
};