递归
- 在二叉搜索树上求最值,求差值等问题,等同于在有序数组上求最值,求差值
- 将二叉搜索树转换为有序数组
class Solution {
vector<int> vec;
private:
void traversal(TreeNode* root){
if(root==nullptr) return;
traversal(root->left);
vec.push_back(root->val);
traversal(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
traversal(root);
int result=100000;
for(int i=1;i<vec.size();i++){
result=min(result,vec[i]-vec[i-1]);
}
return result;
}
};
递归
class Solution {
int result=INT_MAX;
TreeNode* pre;
private:
void traversal(TreeNode* root){
if(root==nullptr) return;
traversal(root->left);
if(pre!=nullptr) result=min(result,root->val-pre->val);
pre=root;
traversal(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}
};
迭代法
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* cur=root;
TreeNode* pre=nullptr;
int result=INT_MAX;
while(cur!=nullptr||!st.empty()){
if(cur!=nullptr){
st.push(cur);
cur=cur->left;
}
else{
cur=st.top();
st.pop();
if(pre!=nullptr){
result=min(result,cur->val-pre->val);
}
pre=cur;
cur=cur->right;
}
}
return result;
}
};