代码随想录算法训练营第21天 |第六章 二叉树part07

学习目标:

  • 530.二叉搜索树的最小绝对差
  • 501.二叉搜索树中的众数
  • 236. 二叉树的最近公共祖先

学习内容:

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

https://www.bilibili.com/video/BV1DD4y11779/?vd_source=aecfc9d884d326a8edbdf2f5958916a7

class Solution {
private:
int result = INT_MAX;
TreeNode* pre = NULL;
void traversal(TreeNode* cur) {
    if (cur == NULL) return;
    traversal(cur->left);   // 左
    if (pre != NULL){       // 中
        result = min(result, cur->val - pre->val);
    }
    pre = cur; // 记录前一个
    traversal(cur->right);  // 右
}
public:
    int getMinimumDifference(TreeNode* root) {
        traversal(root);
        return result;
    }
};

错误以及注意事项

  • 第一个方法听懂了,中序遍历后作为数组做。二叉搜索树直观的想法就是使用中序遍历生成一个升序数组,在形成数组后,其他任务就好处理了。与此同时我们需要掌握双指针的方法。
  • 第二个方法对于为什么pre=cur这里还是有点混沌?

501.二叉搜索树中的众数

// 如果不是二叉搜索树,只是普通的树的话,需要遍历
class Solution {
public:
    void searchBST(TreeNode* cur,unordered_map<int,int>& map){
        if(cur == nullptr) 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;
    }

    vector<int> findMode(TreeNode* root) {
        unordered_map<int,int> map;
        vector<int> result;
        if(root==nullptr) 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;


    }
};

错误以及注意事项

  • cmp函数:这是一个静态成员函数,用作 sort 函数的比较函数。它比较两个 pair<int, int> 类型的对象,根据它们的第二个元素(即节点值的出现次数)降序排序。

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

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

错误以及注意事项

  • 左右中的后序遍历方式。


学习时间:

2023.12.21
2024.2.4 开始放寒假了,中间一个多月没有碰leetcode了,开始复建!争取回学校之前把一刷补完 sad

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值