中序遍历是有序数组,最小绝对差也就是相邻结点的差值。
时间复杂度:O(n)。
/**
* 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 {
private:
int ans = INT_MAX;
int pre = -1;
public:
int getMinimumDifference(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode *root) {
if (!root) {
return;
}
dfs(root->left);
if (pre == -1) {
pre = root->val;
} else {
ans = min(ans, abs(root->val-pre));
pre = root->val;
}
dfs(root->right);
}
};