x
求BST树种节点绝对差值的最小值,由BST树的性质可知,中序遍历会得到一个有序数组,显然所求必然是有序数组中所有相邻两数差的最小值。利用递归算法,在遍历的过程中,利用当前节点值和前一节点值(利用pre进行记录)求绝对值更新结果minDiff。
/**
* 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 minDiff = INT_MAX;
int pre = -1;
int getMinimumDifference(TreeNode* root) {
if(root == NULL)
return minDiff;
getMinimumDifference(root->left);
if(pre != -1){
minDiff = min(minDiff,root->val - pre);
}
pre = root-> val;
getMinimumDifference(root->right);
return minDiff;
}
};