题解 | #二叉搜索树最小差值#
二叉搜索树最小差值
http://www.nowcoder.com/practice/f8ac976b49bd450887b9281f315186c7
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
int minDifference(TreeNode* root) {
// write code here
vector<int> res;
solve(root, res);
sort(res.begin(), res.end());
int ans = INT_MAX, n = res.size();
for (int i=1; i<n; ++i) {
ans = min(ans, res[i] - res[i-1]);
}
return ans;
}
private:
void solve(TreeNode* root, vector<int>& res) {
if (!root) {
return;
}
res.push_back(root->val);
solve(root->left, res);
solve(root->right, res);
}
};