530-二叉搜索树的最小绝对差
程序员文章站
2022-04-24 20:44:17
...
/**
* 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) {
vector<int>arr;
inorder(root, arr);
int minNum = arr[1] - arr[0];
for (int i = 2; i < arr.size(); i++) {
if (arr[i] - arr[i - 1] < minNum) {
minNum = arr[i] - arr[i - 1];
}
}
return minNum;
}
void inorder(TreeNode *root, vector<int>&arr) {
if (root == NULL) {
return;
}
inorder(root->left, arr);
arr.push_back(root->val);
inorder(root->right, arr);
}
};