算法训练营第21天|● 530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● 236. 二叉树的最近公共祖先

文档讲解:代码随想录 (programmercarl.com)

视频讲解:代码随想录的个人空间-代码随想录个人主页-哔哩哔哩视频 (bilibili.com)

LeetCode 二叉搜索树的最小绝对差

题目链接:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)

解题思路:中序遍历为递增序列,利用二叉搜索树这一特性保存每次比较的最小差值即可。

class Solution {
public:
    TreeNode* pre=nullptr;
    int res=INT_MAX;
    void travsal(TreeNode* root){
        if(!root)return;
        travsal(root->left);
        if(pre)res=min(res,root->val-pre->val);
        pre=root;
        travsal(root->right);
    }
    int getMinimumDifference(TreeNode* root) {
        travsal(root);
        return res;
    }
};

LeetCode 二叉搜索树中的众数

题目链接:501. 二叉搜索树中的众数 - 力扣(LeetCode)

解题思路:还是中序遍历,随时更新最大值并保存到数组中。

解题代码如下(下面代码来自代码随想录 (programmercarl.com)):

class Solution {
public:
    int count=0;
    int maxcount=0;
    vector<int>res;
    TreeNode*pre=nullptr;
    void travsal(TreeNode* root){
        if(!root)return;
        travsal(root->left);
        if(pre&&pre->val==root->val)count++;
        else count=1;
        pre=root;
        if(count==maxcount)res.push_back(root->val);
        if(count>maxcount){
            res.clear();
            res.push_back(root->val);
            maxcount=count;
        }
        travsal(root->right);
    }
    vector<int> findMode(TreeNode* root) {
        travsal(root);
        return res;
    }
};

 

LeetCode 二叉树的最近公共祖先

题目链接:236. 二叉树的最近公共祖先 - 力扣(LeetCode)

解题思路:后根遍历。

解题代码如下:

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值