刚开始做想要在原函数直接进行递归,由于返回值是int类型,返回的是子树比较的最小值,则需要对子树返回的最小值,前一个节点和当前节点的差值,当前大二最小值四个值进行比较,比较繁琐;在初始化minNum和遇到nullptr返回时,不能返回0,会干扰结果,应当初始化为INT_MAX,这样不论如何都不会影响到结果。
class Solution {
private:
int minNum = INT_MAX;
TreeNode * pre = nullptr;
public:
int getMinimumDifference(TreeNode* root) {
if(root == nullptr){
return INT_MAX;
}
int minNumL = getMinimumDifference(root->left);
int minNumM = INT_MAX;
if(pre != nullptr){
minNumM = abs(root->val - pre->val);
}
pre = root;
int minNumR = getMinimumDifference(root->right);
minNum = min(min(minNum, minNumL), min(minNumR, minNumM));
return minNum;
}
};
如果不适用原函数递归,则只需比较当前节点和前一个节点的差值与当前最小值的大小。
class Solution {
private:
int minNum = INT_MAX;
TreeNode * pre = nullptr;
public:
void traversal(TreeNode* root){
if(root == nullptr){
return;
}
traversal(root->left);
if(pre != nullptr){
minNum = min(minNum, root->val - pre->val);
}
pre = root;
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return minNum;
}
};