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

代码随想录算法训练营第二十三天

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

题目链接:530.二叉搜索树的最小绝对差

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode*pre = nullptr;
    int min_d = INT_MAX;
    int getMinimumDifference(TreeNode* root) {
        if(!root)return 0;
        int left_b = getMinimumDifference(root->left);
        if(pre){
            min_d = min(min_d,root->val-pre->val);
        };
        pre =root;
        int right_b = getMinimumDifference(root->right);
        return min_d;
    }
};

501.二叉搜索树中的众数

题目链接:501.二叉搜索树中的众数
相邻两个节点相等计数器加1,计数大于最大值就更新最大值,然后把之前收集的结果清空,证明之前收集的结果是错的,计数等于最大值就把该节点的值加入结果集

class Solution {
public:
    int countMax = INT_MIN;
    int count = 0;
    TreeNode* pre = nullptr;
    void find(TreeNode* root, vector<int>& result) {
        if (root == nullptr)
            return;
        find(root->left, result);
        if (pre && pre->val == root->val) {
            count++;
        } else { // pre ==null&&相邻节点不等,计数器都要重置
            count = 1;
        }
        if (count > countMax) {
            countMax = count;
            result.clear(); //清空现有结果集,加入新的结果
            result.push_back(root->val);
        } else if (count == countMax) {
            result.push_back(root->val);
        }
        pre = root;
        find(root->right, result);
    }
    vector<int> findMode(TreeNode* root) {
        vector<int> result;
        find(root, result);
        return result;
    }
};

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

题目链接:236. 二叉树的最近公共祖先

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值