LeetCode530. 二叉搜索树的最小绝对差

题目

又是常见的BST,要利用BST的性质,即中序遍历是有序递增序列。

法一、中序遍历

 1 class Solution {
 2 public:
 3     vector<int>res;
 4     void InOrder(TreeNode* p){
 5         if(p!=NULL){
 6             InOrder(p->left);
 7             res.push_back(p->val);
 8             InOrder(p->right);
 9         }
10     }
11     int getMinimumDifference(TreeNode* root) {
12        InOrder(root);
13        int min = INT_MAX;
14        for(int i = 0;i < res.size() - 1;i++){
15            if(abs(res[i]-res[i+1]) < min )
16                 min = abs(res[i]-res[i+1]);
17        }
18        return min;
19     }
20 
21 };

法二、优化后的中序遍历,不开数组,在递归过程中应用pre指针保存前结点。原理同 LeetCode98. 验证二叉搜索树 中使用pre指针来保存前面结点值

 1 class Solution {
 2 public:
 3     int res = INT_MAX;
 4     TreeNode* pre;
 5     void InOrder(TreeNode* root){
 6         if(root!= NULL) {
 7             InOrder(root->left);
 8             if(pre!=NULL) res = min(res,root->val - pre->val);
 9             pre = root;
10             InOrder(root->right);
11         }
12     } 
13     
14     int getMinimumDifference(TreeNode* root) {
15         InOrder(root);
16         return res;
17     }
18 
19 };

总结:BST题目常利用中序遍历和双指针技巧

原文地址:https://www.cnblogs.com/fresh-coder/p/14247870.html