解题思路
- 递归法(利用二叉搜索树的特点)
用中序遍历将二叉搜索树存进数组里,那么将是一个递增序列
(1)确定终止条件: 传入结点为空,就返回空(void函数)
(2)单层递归逻辑:
如果有左孩子,就递归左孩子;左
将中间结点压入数组;中
如果有右孩子,就递归右孩子。右
(3)无返回值
然后将遍历数组,求相邻之差最小的值。
class Solution {
public:
vector<int>res;
void travalsal(TreeNode* root){
if(!root)return;
if(root->left)travalsal(root->left);//左
res.push_back(root->val);//中
if(root->right)travalsal(root->right);//右
}
int getMinimumDifference(TreeNode* root) {
//递归法
if(!root)return {};
travalsal(root);
int ans=INT_MAX;
for(int i=1;i<res.size();i++){
if(res[i]-res[i-1]<ans){
ans=res[i]-res[i-1];
}
}
return ans;
}
};
- 迭代法
中序遍历的迭代写法:同时引入双指针的思想,计算相邻两结点的差值,保留较小的值。
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
//迭代法:中序遍历
stack<TreeNode*>st;
TreeNode* pre=nullptr;
int minvalue=INT_MAX;
TreeNode* cur=root;
//st.push(root);
while(cur || !st.empty()){
if(cur){
st.push(cur);
cur=cur->left;
}
else{
cur=st.top();
st.pop();
//双指针cur、pre
if(pre){
int a =cur->val-pre->val;
if(a<minvalue)minvalue=a;
}
pre=cur;//指针的更新
cur=cur->right;
}
}
return minvalue;
}
};