代码随想录算法训练营第十九天| 530.二叉搜索树的最小绝对差 501.二叉搜索树中的众数 236. 二叉树的最近公共祖先

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

1. 这题的关键在于二叉搜索树的中序遍历就是 有序序列。

class Solution {
private:
    vector<int> vec;
    void traversal(TreeNode* root){
        if(root==NULL) return;
        //中序遍历树,得到有序序列
        traversal(root->left);
        vec.push_back(root->val);
        traversal(root->right);
    }
public:
    int getMinimumDifference(TreeNode* root) {
        int min=INT_MAX;
        int temp=0;
        vec.clear();
        traversal(root);
        //遍历数组
        for(int i=0,j=1;j<vec.size();i++,j++)
        {
            temp=abs(vec[i]-vec[j]);//可以不用加绝对值,这个是有序序列
            min=(temp<min?temp:min);
        }
        return min;
    }
};

501.二叉搜索树中的众数

1. 使用map来统计频率

class Solution {
private:
    vector<int> vec;
    void traversal(TreeNode* root){
        if(root==NULL) return;
        //中序遍历树,得到有序序列
        traversal(root->left);
        vec.push_back(root->val);
        traversal(root->right);
    }
public:
    vector<int> findMode(TreeNode* root) {
        vector<int> result;
        map<int,int> m1;
        traversal(root);
        for(int i=0;i<vec.size();i++)
        {
            m1[vec[i]]+=1;
        }
        int maxCount = 0;
        for (auto it = m1.begin(); it != m1.end(); ++it) {
            if (it->second > maxCount) {
                maxCount = it->second;
                result.clear();
                result.push_back(it->first);
            } else if (it->second == maxCount) {
                result.push_back(it->first);
            }
        }
        return result;
    }
};

236. 二叉树的最近公共祖先

1.对回溯和递归弄不太清楚可以画图。这题沾点背答案的性质。

2. 模拟整个过程,可以加深理解。不理解模拟多了也理解了。

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==NULL||root==p||root==q) return root;
        TreeNode* left=lowestCommonAncestor(root->left,p,q);
        TreeNode* right=lowestCommonAncestor(root->right,p,q);
        if(right!=NULL&& left!=NULL) return root;
        else if(right!=NULL && left==NULL) return right;
        else if(left!=NULL && right==NULL) return left;
        else {
            return NULL;
        } 
    }
};

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值