【刷题】代码随想录算法训练营第二十一天|530、二叉搜索树的最小绝对差,501、二叉搜索树种的众数,236、二叉树的最近公共祖先

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

讲解:https://programmercarl.com/0530.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E7%BB%9D%E5%AF%B9%E5%B7%AE.html

二叉搜索树是有序的,中序遍历变成一个有序数组,然后在有序数组上求最值。

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) {
        vec.clear();
        traversal(root);
        if(vec.size() < 2) return 0;
        int result = INT_MAX;
        for(int i=1; i<vec.size(); i++){
            result = min(result, vec[i] - vec[i-1]);
        }
        return result;
    }
};

501、二叉搜索树种的众数

讲解:https://programmercarl.com/0501.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E4%BC%97%E6%95%B0.html

见讲解链接。

class Solution {
private:
    void searchBST(TreeNode* cur, unordered_map<int, int>& map){
        if (cur == NULL) return;
        map[cur->val]++;
        searchBST(cur->left, map);
        searchBST(cur->right, map);
        return ; 
    }
    bool static cmp (const pair<int, int>& a, const pair<int, int>& b){
        return a.second > b.second;
    }

public:
    vector<int> findMode(TreeNode* root) {
        unordered_map<int, int> map; // key:元素,value:出现频率
        vector<int> result;
        if (root == NULL) return result;
        searchBST(root, map);
        vector<pair<int, int>> vec(map.begin(), map.end());
        sort(vec.begin(), vec.end(), cmp); // 给频率排个序
        result.push_back(vec[0].first);
        for (int i = 1; i < vec.size(); i++) {
            // 取最高的放到result数组中
            if (vec[i].second == vec[0].second) result.push_back(vec[i].first);
            
            else break;
        }
        return result;
    }
};

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

讲解:https://programmercarl.com/0236.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88.html

没懂,第二天早上再看看,今天有点累。

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-04-24 05:46:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-24 05:46:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-24 05:46:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-24 05:46:02       18 阅读

热门阅读

  1. python排序方法的相关介绍

    2024-04-24 05:46:02       11 阅读
  2. 设计与运营电商系统:构建成功的电商平台

    2024-04-24 05:46:02       10 阅读
  3. C#中的delegate和event,及他们的区别

    2024-04-24 05:46:02       10 阅读
  4. docker swoole+php8.2

    2024-04-24 05:46:02       10 阅读
  5. linux复习提纲

    2024-04-24 05:46:02       11 阅读
  6. 如何在 Ubuntu 上启用 IPv6

    2024-04-24 05:46:02       12 阅读
  7. 十几个好用的学习以及AI网站

    2024-04-24 05:46:02       13 阅读
  8. python使用selenium如何获取一个div下所有的文本

    2024-04-24 05:46:02       11 阅读
  9. AlgorithmDay20

    2024-04-24 05:46:02       11 阅读
  10. 再谈癌症基础与转化研究中的大数据科学

    2024-04-24 05:46:02       13 阅读