LeetCode 530二叉搜索树的最小绝对差_树结构

题目链接:力扣

思路:

中序遍历

二叉搜索树中序遍历是递增序列,要找最小绝对差,就是要找按照中序遍历,后一个数-前一个数的最小值

1.用vector数组保存中序遍历序列

class Solution {
public:
   vector<int>res;
   void inorder(TreeNode *root)
   {
       if(root==NULL)
       {
           return ;
       }
       inorder(root->left);
       res.push_back(root->val);
       inorder(root->right);
   }
    int getMinimumDifference(TreeNode* root) {
inorder(root);
int mini=100000;
for(int i=0;i<res.size()-1;i++)
{
  mini=min(res[i+1]-res[i],mini);
}
return mini;

    }
};

2.用pre指针保存上一个节点

class Solution {
public:
 int mini=100000;
 TreeNode *pre;
   void inorder(TreeNode *root)
   {
       
       if(root==NULL)
       {
           return ;
       }
       inorder(root->left);
       if(pre!=NULL)
       {
           mini=min(mini,root->val-pre->val);
       }
       pre=root;
       inorder(root->right);
   }
    int getMinimumDifference(TreeNode* root) {
inorder(root);

return mini;

    }
};