1.530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
2.注意模板:二叉树绝对值差值最小的只可能是本节点和上一个节点,可以通过列举得出
/**
* 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:
int minNum = INT_MAX;
TreeNode* pre;
int getMinimumDifference(TreeNode* root) {
if(root == nullptr) return 0;
getMinimumDifference(root->left);
if(pre != nullptr){
minNum = min(minNum, abs(pre->val - root->val));
}
pre = root;
getMinimumDifference(root -> right);
return minNum;
}
};